题目描述
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]
]
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
题解
和上一题39. Combination Sum不同,数组中每个数字只能使用一次;但解法类似。使用回溯法。
先对数组进行排序,然后设定一个指针idx指向可以取数的起始位置,然后逐个尝试添加,同时对target减去添加的值,此外,当添加的值等于上一个值时,跳过,防止数字的重复使用;当变为0时,说明已经找到一组解;加入到最终结果数组中,并返回,继续递归;当target小于0时,说明没找到解,弹出元素,继续递归。
完整代码:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> temp;
sort(candidates.begin(), candidates.end());
backtracking(result, temp, candidates, target, 0);
return result;
}
private:
void backtracking(vector<vector<int>>& result, vector<int>& temp, vector<int>& nums, int remain, int start){
if(remain < 0) return;
else if(remain == 0) result.push_back(temp);
else{
for(int i=start; i<nums.size(); i++){
if(i>start && nums[i] == nums[i-1]) continue;
temp.push_back(nums[i]);
backtracking(result, temp, nums, remain-nums[i], i+1);
temp.pop_back();
}
}
}
};