Python Leetcode 78-发电机组时间复杂性
Leetcode 78潜在解决方案:Python Leetcode 78-发电机组时间复杂性,python,algorithm,time-complexity,code-complexity,Python,Algorithm,Time Complexity,Code Complexity,Leetcode 78潜在解决方案: class Solution(object): def __init__(self): self.map = {} def helper(self, count, nums, vals, result): if count == 0: result += [vals] for i in r
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
来确定复杂度帮助程序调用了多少次,代码方面如下所示:
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
调用helper函数的时间
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)