-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathjoon.py
34 lines (30 loc) · 1.14 KB
/
joon.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
33
34
from typing import List
from typing import Set
from typing import Tuple
class Solution:
target: int
candidates: List[int]
answers: Set[Tuple[int]]
# Time: O(k^N)
# Space: O(N^2)
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.target = target
self.candidates = candidates
self.answers = set()
self.findAnswers(0, [])
return list(self.answers)
def findAnswers(self, currentSum: int, nums: List[int]):
assert currentSum < self.target, "Given sum should be smaller than the target."
for num in self.candidates:
if currentSum + num < self.target:
# 1. Continue finding.
# Time: O(k^N)
# Space: O(N^2). Max total size of all "nums" = 1 + 2 + ... + N.
self.findAnswers(currentSum + num, nums + [num])
if currentSum + num > self.target:
# 2. Stop finding.
continue
if currentSum + num == self.target:
# 3. Add the answer.
self.answers.add(tuple(sorted(list(nums + [num]))))
return