Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 这个agorithm(解决leetcode问题650)的时间复杂度是多少?_Python 3.x_Algorithm_Data Structures_Dynamic Programming_Bottom Up - Fatal编程技术网

Python 3.x 这个agorithm(解决leetcode问题650)的时间复杂度是多少?

Python 3.x 这个agorithm(解决leetcode问题650)的时间复杂度是多少?,python-3.x,algorithm,data-structures,dynamic-programming,bottom-up,Python 3.x,Algorithm,Data Structures,Dynamic Programming,Bottom Up,您好,我一直在研究这个动态规划问题 在空白页上以“A”开头,然后得到一个数字n,完成后,页面上应该有n次“A”。问题是,您只允许进行两次操作:复制(并且您只能复制页面上当前A的总量)和粘贴-->查找要在页面上获得n'A'的最小操作数 我写了下面的算法来解决这个问题,但是我很难分析它的时间复杂度 代码如下: def minSteps(self, n: int) -> int: DP = [0] + [0] + [i for i in range(2, n+1)]

您好,我一直在研究这个动态规划问题

在空白页上以“A”开头,然后得到一个数字
n
,完成后,页面上应该有
n
次“A”。问题是,您只允许进行两次操作:复制(并且您只能复制页面上当前A的总量)和粘贴-->查找要在页面上获得
n
'A'的最小操作数

我写了下面的算法来解决这个问题,但是我很难分析它的时间复杂度

代码如下:

    def minSteps(self, n: int) -> int:
        DP = [0] + [0] + [i for i in range(2, n+1)]

        for d in range(2, n+1):
            for i in range(d*2, n+1, d):
                DP[i] = min(DP[i], DP[d] + i//d )
        return DP[n]
所以我的直觉告诉我,这个算法介于
O(n^2)
O(nlogn)
之间,因为在第二个循环中,我们比
O(n)
要“快”,但是由于步长
d
在每次迭代之间没有翻倍,所以在第二个循环中仍然是
O(n)


我不知道如何分析该循环,欢迎提供任何帮助。

让我们看看外部循环-它执行了
O(N)
次。
每个内部循环都在执行
O(N/d)
操作,因为索引的跳转在
d

因此,计算如下:

N / 1 + N / 2 + N / 3 + ... + 1
请注意,此总和中有
N

我们可以将
N
取出:

N * (1 / 1 + 1 / 2 + 1 / 3 + ... + 1 / N)
大约是:

N * ln N
(直观地说,通过集成函数
1/N
,可以得到
ln

因此,总体来说,复杂性是
O(nlogn)

您的解决方案是
O(nlogn)
。以下是一个更有效的解决方案:

 def minSteps(self, n: int) -> int:
        ans = 0
        d = 2
        while n >= d * d:
            while n % d == 0:
                ans += d
                n //= d
            d += 1
        if n != 1:
            ans += n
        return ans 

此解决方案基于LeetCode上发布的解决方案,但速度要快得多。时间复杂度是
O(sqrt(p))
,其中
p
n

的最大素因子。如果最后一步不清楚,请查找“调和数”