1
+ # Given an array of distinct integers candidates and a target integer target,
2
+ # return a list of all unique combinations of candidates where the chosen
3
+ # numbers sum to target. You may return the combinations in any order.
4
+
5
+ # The same number may be chosen from candidates an unlimited number of times.
6
+ # Two combinations are unique if the
7
+ # frequency
8
+ # of at least one of the chosen numbers is different.
9
+
10
+ # The test cases are generated such that the number of unique combinations that
11
+ # sum up to target is less than 150 combinations for the given input.
12
+
13
+
14
+ # Example 1:
15
+ # Input: candidates = [2,3,6,7], target = 7
16
+ # Output: [[2,2,3],[7]]
17
+ # Explanation:
18
+
19
+ # 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
20
+ # 7 is a candidate, and 7 = 7.
21
+ # These are the only two combinations.
22
+
23
+ # Example 2:
24
+ # Input: candidates = [2,3,5], target = 8
25
+ # Output: [[2,2,2,2],[2,3,3],[3,5]]
26
+
27
+ # Example 3:
28
+ # Input: candidates = [2], target = 1
29
+ # Output: []
30
+
31
+
32
+ # Constraints:
33
+
34
+ # 1 <= candidates.length <= 30
35
+ # 2 <= candidates[i] <= 40
36
+ # All elements of candidates are distinct.
37
+ # 1 <= target <= 40
38
+
39
+
40
+ from typing import List
41
+ class Solution :
42
+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
43
+ ans = []
44
+ def dfs (s , t , path : list [int ]):
45
+ if t < 0 :
46
+ return
47
+ if t == 0 :
48
+ ans .append (path .copy ())
49
+ for i in range (s , len (candidates )):
50
+ path .append (candidates [i ])
51
+ dfs (i , t - candidates [i ], path )
52
+ path .pop ()
53
+ dfs (0 , target , [])
54
+ return ans
0 commit comments