File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments