题目链接:https://leetcode.com/problems/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 10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:和39. Combination Sum差不多,只是这个每个数只能用一次,值得注意的是相同的数如果不做判断可能会产生相同的序列。因此在同一层的递归中,应当跳过重复的数。
代码如下:
class Solution {
public:
void DFS(vector<int>& candidates, int target, vector<int> vec, int sum, int k)
{
if(sum == target) result.push_back(vec);
if(k >= candidates.size() || sum >= target) return;
vec.push_back(candidates[k]);
DFS(candidates, target, vec, sum+candidates[k], k+1);
while(k<candidates.size()-1 && candidates[k] == candidates[k+1]) k++;
vec.pop_back();
DFS(candidates, target, vec, sum, ++k);
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
if(candidates.size() ==0) return {};
sort(candidates.begin(), candidates.end());
DFS(candidates, target, vector<int>{}, 0, 0);
return result;
}
private:
vector<vector<int>> result;
};