-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0040_Combination_Sum_II.py
More file actions
30 lines (22 loc) · 936 Bytes
/
0040_Combination_Sum_II.py
File metadata and controls
30 lines (22 loc) · 936 Bytes
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
'''
Problem: https://leetcode.com/problems/combination-sum-ii/
Runtime: 75 ms (better than 91%)
Memory: 14 MB
'''
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
combos = set()
def helper(candidates: tuple[int], curr_val: int, curr_nums: tuple[int]) -> None:
for i, n in enumerate(candidates):
if i > 0 and n == candidates[i-1]: continue
new_val = curr_val + n
if new_val < target and candidates:
helper(candidates[i+1:], new_val, curr_nums + tuple([n]))
elif new_val == target:
combos.add(tuple(curr_nums + tuple([n])))
break
elif new_val > target:
break
candidates = tuple(sorted(x for x in candidates if x <= target))
helper(candidates, 0, ())
return combos