Leetcode 78 - 生成幂集时间复杂度

Leetcode 78 - Generate power set time complexity

Leetcode 78 question 可能的解决方案:

class Solution(object):
    def __init__(self):
        self.map = {}
    
    def helper(self, count, nums, vals, result):       
        
        if count == 0:
            result += [vals]        
            
        for i in range(len(nums)):
            self.helper(count - 1, nums[i+1:], vals + [nums[i]], result)
        
    
    def subsets(self, nums):
        result = []
        result.append([])
        
        for count in range(1,len(nums)+1):
            self.helper(count, nums, [], result)   
            
        return result

对于上面的解法,时间复杂度是O(2^n)还是O(n * 2^n)?

可以通过查找不同的 N 来找出复杂度 helper 函数被调用了多少次,代码方面如下所示:

class Solution(object):

    def __init__(self):
        self.map = {}
        self.counter = 0

    def helper(self, count, nums, vals, result):
        self.counter += 1
        if count == 0:
            result += [vals]

        for i in range(len(nums)):
            self.helper(count - 1, nums[i + 1:], vals + [nums[i]], result)

    def subsets(self, nums):
        result = [[]]

        for count in range(1, len(nums) + 1):
            self.helper(count, nums, [], result)

        return self.counter

因此:

N Time the helper function gets called
1 2
2 8
3 24
4 64
5 160
6 384
7 896
8 2048
9 4608
10 10240
... ....
N O(n * 2^n)

helper 函数的复杂度为 O(2^n),因为您调用了列表的每个元素 nums:

for count in range(1,len(nums)+1):
    self.helper(count, nums, [], result)  

整体时间复杂度为O(n * 2^n)