【问题标题】:Why is time complexity O(n!) not O(n * n!)为什么时间复杂度 O(n!) 不是 O(n * n!)
【发布时间】:2021-06-23 19:13:02
【问题描述】:

这是一个link to a youtube video @ 11:50,它显示了以下递归树:

代码类似于:

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        
        def helper(curr: List[int], remains: List[int], res: List[List[int]]):
            if not remains:
                res.append(curr)
                return
            
            for i in range(len(remains)):
                next_num = remains[i]
                helper(curr + [next_num], [num for num in remains if num != next_num], res)
                
        helper([], nums, res)
        return 

视频说有 O(n!) 函数调用,但它似乎有点多所以可能大致是这样,但是在每一步中我们必须在最坏的情况下复制 n新剩余数组的元素,那为什么不变成 O(n * n!)

【问题讨论】:

    标签: python algorithm permutation


    【解决方案1】:

    对于n-参数列表,helper 对具有n-1 元素的列表进行n 递归调用。这意味着它的运行时间是 T(n) = n*T(n-1)。求解 T 会产生 n!,如果您自己展开几轮就很明显了:

    T(n) = n * T(n-1)
         = n * (n-1) * T(n-2)
         = n * (n-1) * (n-2) * T(n-3)
         = ...
         = n! * T(0)
    

    如果它对n-1 元素的列表进行一个递归调用,将是 O(n*n)。

    【讨论】:

    • 所以我们不在乎每次调用复制一个新数组所花费的时间?
    • 我们有,我们没有。 (对不起,我误读了O(n*n!)O(n*n)。)等式应该是T(n) = n*T(n-1) + O(n^2),这.. 可能适用于O(n*n!)?但是,O(n!) 和 O(n*n!) 之间并没有太大的实际区别;两者都是指数级的,所以非常慢。也就是说,可以通过使用一种不同的数据结构来消除n 的因素,这种数据结构可以让您在 O(1) 时间内删除给定的值,而不必用每个元素重建集合 but i> 给定的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2013-10-20
    • 2021-08-13
    • 2020-06-25
    • 2015-05-25
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多