|
| 1 | +/* |
| 2 | +Combination Sum |
| 3 | +=============== |
| 4 | +
|
| 5 | +Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. |
| 6 | +
|
| 7 | +The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. |
| 8 | +
|
| 9 | +It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: candidates = [2,3,6,7], target = 7 |
| 13 | +Output: [[2,2,3],[7]] |
| 14 | +Explanation: |
| 15 | +2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. |
| 16 | +7 is a candidate, and 7 = 7. |
| 17 | +These are the only two combinations. |
| 18 | +
|
| 19 | +Example 2: |
| 20 | +Input: candidates = [2,3,5], target = 8 |
| 21 | +Output: [[2,2,2,2],[2,3,3],[3,5]] |
| 22 | +
|
| 23 | +Example 3: |
| 24 | +Input: candidates = [2], target = 1 |
| 25 | +Output: [] |
| 26 | +
|
| 27 | +Example 4: |
| 28 | +Input: candidates = [1], target = 1 |
| 29 | +Output: [[1]] |
| 30 | +
|
| 31 | +Example 5: |
| 32 | +Input: candidates = [1], target = 2 |
| 33 | +Output: [[1,1]] |
| 34 | +
|
| 35 | +Constraints: |
| 36 | +1 <= candidates.length <= 30 |
| 37 | +1 <= candidates[i] <= 200 |
| 38 | +All elements of candidates are distinct. |
| 39 | +1 <= target <= 500 |
| 40 | +*/ |
| 41 | + |
| 42 | +class Solution |
| 43 | +{ |
| 44 | +public: |
| 45 | + void dfs(vector<int> &arr, int sum, int i, vector<int> atn, vector<vector<int>> &ans) |
| 46 | + { |
| 47 | + if (sum == 0) |
| 48 | + { |
| 49 | + ans.push_back(atn); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if (sum < 0) |
| 54 | + return; |
| 55 | + for (int j = i; j < arr.size(); ++j) |
| 56 | + { |
| 57 | + atn.push_back(arr[j]); |
| 58 | + dfs(arr, sum - arr[j], j, atn, ans); |
| 59 | + atn.pop_back(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + vector<vector<int>> combinationSum(vector<int> &candidates, int target) |
| 64 | + { |
| 65 | + vector<vector<int>> ans; |
| 66 | + dfs(candidates, target, 0, {}, ans); |
| 67 | + return ans; |
| 68 | + } |
| 69 | +}; |
0 commit comments