Combination Sum II
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]
解题思路:在combine sum I的基础上加一个集合
class Solution {
public:
//t目标数组 i当前下标 sum当前选中元素之和 vi暂存元素容器 vvi目标存储位置
void innerCS(vector<int> &t, int i, int sum, int target, vector<int> &vi, vector<vector<int> > &vvi, set<vector<int> > &svi){
int n = t.size();
if(sum == target && svi.insert(vi).second) {//集合的使用
vvi.push_back(vi);
return;
}
if(sum > target || i == n) return; //剪支
for(int j = i; j < n; j++){
vi.push_back(t[j]);
innerCS(t, j + 1, sum + t[j], target, vi, vvi, svi); //j变成了j + 1
vi.pop_back();
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int> > vvi;
int n = num.size();
if(n == 0) return vvi;
sort(num.begin(), num.end());
vector<int> t;
set<vector<int> > svi;
for(int i = 0; i < n; i++){
if(num[i] > target) break;
t.push_back(num[i]); //一定情况下的减支
}
vector<int> vi;
innerCS(t, 0, 0, target, vi, vvi, svi);
return vvi;
}
};