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.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
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]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> temp;
vector<vector<int>> res;
sort(candidates.begin(),candidates.end());
backtrack(candidates,res,temp,target,0);
return res;
}
void backtrack(vector<int>& candidates,vector<vector<int>> &res,vector<int> &temp,int remain,int start){
if(remain<0) return;
else if(remain==0) res.push_back(temp);
else{
for(int i=start;i<candidates.size();i++){
if(i>start && candidates[i-1]==candidates[i]) continue;
temp.push_back(candidates[i]);
backtrack(candidates,res,temp,remain-candidates[i],i+1);
temp.pop_back();
}
}
}
};
1 刚开始没有写remain<0,导致time limit exceeded,因为如果是一个很小的target,和一群很大的vector数,会导致它会计算负数,
2 刚开始没有写if(i>start && candidates[i-1]==candidates[i]) continue; 这个条件是控制第二次大循环过滤掉相同的元素[1,1,2,5,6,7,10]过滤掉第二个1