Skip to content

Commit aa833bb

Browse files
author
wuduhren
committed
combination-sum
1 parent 3856e22 commit aa833bb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

problems/python3/combination-sum.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Time: O(N^K), assuming the number of element in the combination that sums up to "target" is K.
3+
For each element, there is N choices.
4+
Which means the number of combination is N*N*N... for K times.
5+
~= O(N^K)
6+
7+
Space: O(K)
8+
9+
K is approximate to target/min(candidates).
10+
"""
11+
class Solution:
12+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
13+
def helper(i, currSum, target):
14+
if currSum>target:
15+
return
16+
17+
if currSum==target:
18+
ans.append(combination.copy())
19+
return
20+
21+
for j in range(i, len(candidates)):
22+
combination.append(candidates[j])
23+
helper(j, currSum+candidates[j], target)
24+
combination.pop()
25+
26+
ans = []
27+
combination = []
28+
helper(0, 0, target)
29+
return ans

0 commit comments

Comments
 (0)