Skip to content

Commit 23966d5

Browse files
committed
add solution: combination-sum
1 parent 78d9149 commit 23966d5

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

combination-sum/dusunax.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
# 39. Combination Sum
3+
4+
Backtracking for find combinations.
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(n^2)
10+
SC: O(n)
11+
```
12+
13+
#### TC is O(n^2):
14+
- iterating through the list in backtracking recursion to find combinations. = O(n^2)
15+
16+
#### SC is O(n):
17+
- using a list to store the combinations. = O(n)
18+
'''
19+
20+
class Solution:
21+
# Backtracking = find combination
22+
# candidate is distinct & can use multiple times.
23+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
24+
result = []
25+
26+
def backtrack(currIdx, remain, combination):
27+
if(remain == 0):
28+
result.append(combination[:])
29+
return
30+
if(remain < 0):
31+
return
32+
33+
for i in range(currIdx, len(candidates)):
34+
combination.append(candidates[i])
35+
backtrack(i, remain - candidates[i], combination)
36+
combination.pop()
37+
38+
backtrack(0, target, [permutations])
39+
return result

0 commit comments

Comments
 (0)