给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
这个题和组合总和第一个题基本一样,就是要在搜索下一个数的时候不要从本次这个数开始,而是从下一个数开始,也就是递归的时候传递的值变为i+1。而且有可能会有重复的数,所以for循环的时候跳过重复的数。
C++源代码:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> out;
sort(candidates.begin(), candidates.end());
combinationSum2DFS(candidates, target, 0, out, res);
return res;
}
void combinationSum2DFS(vector<int>& candidates, int target, int start, vector<int>& out, vector<vector<int>>& res) {
if(target < 0) return;
else if(target == 0) {res.push_back(out); return;}
for(int i=start;i<candidates.size();i++){
if(i>start && candidates[i]==candidates[i-1]) continue;
out.push_back(candidates[i]);
combinationSum2DFS(candidates, target-candidates[i], i+1, out, res);
out.pop_back();
}
}
};
python3源代码:
class Solution:
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
out = []
candidates.sort()
self.combinationSum2DFS(candidates, target, 0, out, res)
return res
def combinationSum2DFS(self, candidates, target, start, out, res):
if target < 0:
return
elif target == 0:
res.append(copy.deepcopy(out))
return
for i in range(start, len(candidates)):
if i>start and candidates[i]==candidates[i-1]:
continue
out.append(candidates[i])
self.combinationSum2DFS(candidates, target-candidates[i], i+1, out, res)
out.pop()