File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import List
2+ from typing import Set
3+ from typing import Tuple
4+
5+
6+ class Solution :
7+ target : int
8+ candidates : List [int ]
9+ answers : Set [Tuple [int ]]
10+
11+ # Time: O(k^N)
12+ # Space: O(N^2)
13+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
14+ self .target = target
15+ self .candidates = candidates
16+ self .answers = set ()
17+ self .findAnswers (0 , [])
18+ return list (self .answers )
19+
20+ def findAnswers (self , currentSum : int , nums : List [int ]):
21+ assert currentSum < self .target , "Given sum should be smaller than the target."
22+ for num in self .candidates :
23+ if currentSum + num < self .target :
24+ # 1. Continue finding.
25+ # Time: O(k^N)
26+ # Space: O(N^2). Max total size of all "nums" = 1 + 2 + ... + N.
27+ self .findAnswers (currentSum + num , nums + [num ])
28+ if currentSum + num > self .target :
29+ # 2. Stop finding.
30+ continue
31+ if currentSum + num == self .target :
32+ # 3. Add the answer.
33+ self .answers .add (tuple (sorted (list (nums + [num ]))))
34+ return
You can’t perform that action at this time.
0 commit comments