-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombination_Sum_Day54.py
More file actions
52 lines (40 loc) · 1.17 KB
/
Copy pathCombination_Sum_Day54.py
File metadata and controls
52 lines (40 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#Brute Approach
class Solution:
def combinationSum(self, candidates, target):
res = []
n = len(candidates)
def generate(idx, curr):
if idx == n:
if sum(curr) == target:
res.append(curr[:])
return
# pick the element
curr.append(candidates[idx])
generate(idx, curr)
curr.pop()
# skip the element
generate(idx + 1, curr)
generate(0, [])
return res
# TC - O(2^n * n)
# SC - O(n)
#Better Approach
class Solution:
def combinationSum(self, candidates, target):
res = []
n = len(candidates)
def dfs(idx, curr, total):
# base case
if total == target:
res.append(curr[:])
return
if total > target or idx >= n:
return
# pick the element (can pick multiple times)
curr.append(candidates[idx])
dfs(idx, curr, total + candidates[idx])
curr.pop()
# skip the element
dfs(idx + 1, curr, total)
dfs(0, [], 0)
return res