题目:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
解答:
class Solution {
private:
void backtracking(vector<int>& candidates, int target, int pos, vector<int>& temp, vector<vector<int>>& result)
{
int n = candidates.size();
if(target==0)
result.push_back(temp);
if(pos>=n || target<=0)
return;
int nextPos = pos+1;
while(nextPos<n && candidates[nextPos]==candidates[pos])
{
nextPos++;
}
int i, j;
for(i=0; i<=nextPos-pos; i++)
{
if(target-i*candidates[pos]<0)
break;
for(j=0; j<i; j++)
temp.push_back(candidates[pos]);
backtracking(candidates, target-i*candidates[pos], nextPos, temp, result);
for(j=0; j<i; j++)
temp.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int> temp;
vector<vector<int>> result;
backtracking(candidates, target, 0, temp, result);
return result;
}
};