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()==0) return res; vector<int> temp; helper(candidates,0,target,temp); return res; } private: void helper(vector<int>& candidates,int index,int target,vector<int>& temp){ if(target==0) res.push_back(temp); if(target<0 || index>=candidates.size()){ return; } for(int i=index;i<candidates.size();i++) { if(i>index && candidates[i]==candidates[i-1])//必须保证第一个位置以一个数值递归下去时不能重复!但第一次遍历时又必须保存,所以必须写成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+1,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,1,k,temp,k); return res; } void helper(int n,int pos,int k,vector<int>& temp,int count){ if(0==count){ res.push_back(temp); return; } if(pos>n||count<0) return; for(int i=pos;i<=n;i++){ temp.push_back(i); helper(n,i+1,k,temp,--count);//这个地方写成i+1而不是pos+1 temp.pop_back(); count++; } } private: vector<vector<int>> res; };