Description
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
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]
]
Analyse
这是上一道题的变式,将可以重复选的数字改成了所有的数字只能使用一次,方法同样是DFS,但在这里,必须得进行排序(前一道题排不排序都可以),因为数组里会出现两个或多个相同数字的情况,取的时候,必须把他们的区别性消除掉,否则就会出现这种情况,拿Example 2举个例子,为了区分,我们把相同的2设为2a,2b,2c,那么[1,2,2]就会出现[1,2a,2b],[1,2a,2c],[1,2b,2c],三种情况,这样是不对的,我们可以通过排序来解决这个问题。出现多个的情况,我们只采用最后一个作为代表。
Code
class Solution {
public:
void calcombination(vector<vector<int>> &ans, vector<int> &temp, int target, vector<int>& candidates, int begin) {
if (target == 0) {
ans.push_back(temp);
} else {
for (int i = begin; i < candidates.size(); i++) {
if (candidates[i] > target) break;
if (i != begin && candidates[i] == candidates[i - 1]) continue;
temp.push_back(candidates[i]);
calcombination(ans, temp, target - candidates[i], candidates, i + 1);
temp.pop_back();
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> temp;
calcombination(ans, temp, target, candidates, 0);
return ans;
}
};