https://leetcode.com/problems/combination-sum-ii/
题目跟前面几道题很类似,直接写代码:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
if(candidates.size()==)
return res;
vector<int> temp;
helper(candidates,,target,temp);
return res; }
private:
void helper(vector<int>& candidates,int index,int target,vector<int>& temp){
if(target==)
res.push_back(temp); if(target< || index>=candidates.size()){
return;
} for(int i=index;i<candidates.size();i++)
{
if(i>index && candidates[i]==candidates[i-])//必须保证第一个位置以一个数值递归下去时不能重复!但第一次遍历时又必须保存,所以必须写成i>index,而不是i>0!!就是针对这类情形 1,1,2,5,6,7,10 8 【1,2,5】 【1,2,5】 【1,1,6】
continue;
temp.push_back(candidates[i]);
helper(candidates,i+,target-candidates[i],temp);//注意这个地方就不应该是index了,而应该传入i+1,否则,会出现降序数列
temp.pop_back();
}
}
private:
vector<vector<int>> res;
};
https://leetcode.com/problems/combinations/
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
if(n<k)
return res;
vector<int> temp;
helper(n,,k,temp,k);
return res;
} void helper(int n,int pos,int k,vector<int>& temp,int count){
if(==count){
res.push_back(temp);
return;
}
if(pos>n||count<)
return;
for(int i=pos;i<=n;i++){
temp.push_back(i);
helper(n,i+,k,temp,--count);//这个地方写成i+1而不是pos+1
temp.pop_back();
count++;
}
} private:
vector<vector<int>> res;
};