Problem:
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]
]
思路:
和39题类似的思路,利用递归求解。注意要除去重复的结果。
Solution (C++):
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> combination;
combinationSum2(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum2(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &combination, int begin) {
if (target == 0) {
res.push_back(combination);
return;
}
else {
for (int i = begin; i < candidates.size() && target >= candidates[i]; ++i) {
if (i && candidates[i] == candidates[i-1] && i > begin) continue; //检查是否重复
combination.push_back(candidates[i]);
combinationSum2(candidates, target-candidates[i], res, combination, i+1);
combination.pop_back();
}
}
}
性能:
Runtime: 8 ms Memory Usage: 8.9 MB