问题描述:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
问题分析:
与39题类似,但是数列中重复的数字只能使用一个,结果不能出现重复的数列。
问题求解:
class Solution {
private:
void dfs(vector<vector<int> > &ans, vector<int> &single,
vector<int> &candi, int cur, int rest) {
int sz = candi.size();
if (rest == 0) {
ans.push_back(single);
return;
}
else{
for( int i = cur; i < sz; i++){
if(candi[i] > rest) return;
if(i && candi[i] == candi[i -1] && i > cur) continue;
single.push_back(candi[i]);
dfs(ans, single, candi, i+1,rest-candi[i]);
single.pop_back();
}
}
}
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > ans;
vector<int> single;
sort(num.begin(), num.end());
dfs(ans, single, num, 0, target);
return ans;
}
};