Combination Sum II - LeetCode
题目链接
注意点
- 数字不能重复使用
解法
解法一:和Combination Sum这道一样,递归的时候跳过重复数字,并且参数改为i+1。
class Solution {
public:
void dfs(vector<int>& candidates, int target,vector<int>& v,vector<vector<int>>& ret,int index)
{
if(target < 0) return;
if(target == 0)
{
ret.push_back(v);
return;
}
for(int i = index;i < candidates.size();i++)
{
if(candidates[i] <= target)
{
v.push_back(candidates[i]);
dfs(candidates,target-candidates[i],v,ret,i+1);
while(i+1 < candidates.size() && v.back() == candidates[i+1]) ++i;
v.pop_back();
}
else break;
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> ret;
vector<int> v;
dfs(candidates,target,v,ret,0);
return ret;
}
};
小结
- 递归题