-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_combination_sum.py
32 lines (28 loc) · 1.01 KB
/
graph_combination_sum.py
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
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
answer=[]
def dfs(elements:List[int], start:int) :
if sum(elements) == target :
answer.append(elements[:])
return
if sum(elements) > target :
return
for i in candidates[start:]:
elements.append(i)
dfs(elements, candidates.index(i))
elements.pop()
dfs([],0)
return answer
def combinationSumFast(self, candidates: List[int], target: int) -> List[List[int]]:
answer=[]
def dfs(csum, index, path) :
if csum == 0:
answer.append(path)
return
if csum < 0 :
return
for i in range(index, len(cantidates)):
dfs(csum-candidates[i], i, path+[candidates[i]])
dfs(target,0,[])
return answer