-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSumII.cpp
More file actions
31 lines (30 loc) · 1.2 KB
/
combinationSumII.cpp
File metadata and controls
31 lines (30 loc) · 1.2 KB
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
/*Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates
where the candidate numbers sum to target.Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]] */
class Solution {
public:
void findCombination(int ind, int target, vector<int> &arr, vector<vector<int>> &ans, vector<int>&ds) {
if(target==0) {
ans.push_back(ds);
return;
}
for(int i = ind;i<arr.size();i++) {
if(i>ind && arr[i]==arr[i-1]) continue;
if(arr[i]>target) break;
ds.push_back(arr[i]);
findCombination(i+1, target - arr[i], arr, ans, ds);
ds.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
};