Combination Sum II
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
A solution set is:
10,1,2,7,6,1,5
and target 8
,A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
--------------------------- thinking -----------------------------------------
please compare codes between Combination Sum & Combination Sum II
http://bangbingsyb.blogspot.com/2014/11/leetcode-combination-sum-i-ii.html
------------------------------- codes ---------------------------------------
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
vector<vector<int>> result;
vector<int> curSol;
sort(num.begin(), num.end());
combSum(num, 0, curSol, target, result);
return result;
}
void combSum(vector<int>& candidates, int next, vector<int> &curSol, int target, vector<vector<int>> &result) {
if (target == 0) {
result.push_back(curSol);
}
if (next == candidates.size() || candidates[next] > target) {
return;
}
curSol.push_back(candidates[next]);
combSum(candidates, next + 1, curSol, target - candidates[next], result);
curSol.pop_back();
int i = next + 1;
while (i < candidates.size() && candidates[i] == candidates[next]) {
i++;
}
combSum(candidates, i, curSol, target, result);
}
};
No comments:
Post a Comment