|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + |
| 4 | + void combination(int index, int arrSize, int currSum, int target, vector<int>& ds, vector<vector<int>>& ans, vector<int> & arr) { |
| 5 | + if(currSum > target) return; |
| 6 | + |
| 7 | + if(currSum == target){ |
| 8 | + ans.push_back(ds); |
| 9 | + return; |
| 10 | + } |
| 11 | + |
| 12 | + for(int i = index; i < arrSize; i++){ |
| 13 | + if(i > index && arr[i] == arr[i-1]) continue; // skip duplicates |
| 14 | + if(currSum + arr[i] > target) break; // pruning |
| 15 | + |
| 16 | + ds.push_back(arr[i]); |
| 17 | + combination(i + 1, arrSize, currSum + arr[i], target, ds, ans, arr); // i+1 because each element can be used once |
| 18 | + ds.pop_back(); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { |
| 23 | + vector<vector<int>> ans; |
| 24 | + vector<int> ds; |
| 25 | + sort(candidates.begin(), candidates.end()); // sort to handle duplicates and pruning |
| 26 | + combination(0, candidates.size(), 0, target, ds, ans, candidates); |
| 27 | + return ans; |
| 28 | + } |
| 29 | +}; |
0 commit comments