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]
]
这道题目本质上还是Combination Sum 问题的一个变化,其关键之处就在于排除重复项,即本身元素不重复出现,如果同一层出现相同元素则忽视后面的元素。重复项的问题可以用以下一张图片来概括。假设给定的序列 [ 1, 2, 2, 2, 5], 目标值是5,则有:
故而在Combination Sum 答案的基础上进行了改进, 代码如下:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> ans;
sort(candidates.begin(), candidates.end());
if(candidates.empty() || target < candidates[0]) return ans;
vector<int> temp;
tree(ans, candidates, temp, 0, 0, target);
return ans;
}
void tree(vector<vector<int>>& ans, vector<int>& candidates, vector<int>& temp, int last_p, int sum, int target)
{
if(sum == target)
{
ans.push_back(temp);
return;
}
for(int i = last_p; i < candidates.size(); i++)
{
if(sum + candidates[i] > target) break;
if(i != last_p && candidates[i] == candidates[i - 1]) continue;
temp.push_back(candidates[i]);
tree(ans,candidates, temp, i + 1 , sum + candidates[i], target);
temp.pop_back();
}
}
};