和第39题是同宗同源。
上次是数组没有重复数字,这次允许有重复数字:
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
例子:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
做法类似:注意细节
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>>res;
vector<int>tmp;
sort(candidates.begin(),candidates.end());
dfs(candidates,0,res,tmp,target);
return res;
}
void dfs(vector<int>& candidates,int start,vector<vector<int>>&res,vector<int>&tmp,int target )
{
if(!target)
{
res.push_back(tmp);
return;
}
for(int i = start;i!=candidates.size()&&target>=candidates[i];i++)
{
if(i==start || candidates[i]!=candidates[i-1])
{
tmp.push_back(candidates[i]);
dfs(candidates,i+1,res,tmp,target-candidates[i]);
tmp.pop_back();
}
}
}
};