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

问题描述

Leetcode 78 question 潜在解决方案:

5
5
5
5
5
5
5
5
5
...
2
2
2
2
2

对于上面的解决方案,时间复杂度是 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,[],result)

        return self.counter

所以:

N 调用辅助函数的时间
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,result)  

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