题目:
40. Combination Sum II
Medium
64034FavoriteShare
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[10,1,2,7,6,1,5]
, target =8
, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5, A solution set is: [ [1,2,2], [5] ]
代码:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> m;
if (target < 0)return m;
if (target == 0) {
vector<int> v;
m.push_back(v);
return m;
}
int len = candidates.size();
for (int i = 0; i < len; i++) {
int value = candidates[i];
candidates[i] = candidates[len - 1];
candidates[len - 1] = value;
candidates.pop_back();
vector<vector<int>> v = combinationSum2(candidates, target - value);
if (v.size() != 0) {
for (int j = 0; j < v.size(); j++) {
v[j].push_back(value);
sort(v[j].begin(), v[j].end());
m.push_back(v[j]);
}
}
candidates.push_back(value);
int temp = value;
candidates[len - 1] = candidates[i];
candidates[i] = temp;
}
sort(m.begin(), m.end());
m.erase(unique(m.begin(), m.end()),m.end());
return m;
}
};