题目:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
- 所有数字(包括目标数)都是正整数。
- 解集不能包含重复的组合。
例:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
来源:
解题思路:回溯
继续学习回溯,
- 递归终止条件:当前sum大于等于target
- 结果满足条件:sum == target
- 剪枝条件:当前sum即将超过目标值
- 结果不重复:在遍历数组时,跳过相同的数字(此时递归并没有跳过相同的数字)
c++代码:
class Solution {
public:
vector< vector<int> > result;
vector<int> path;
vector< vector<int> > combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
back(candidates, 0, 0, target);
return result;
}
void back(const vector<int>& candidates, int start, int sum, int target) {
if (sum == target) { // 结果
result.push_back(path);
return;
}
for (int i = start; i < candidates.size(); i++) {
if (sum + candidates[i] > target) break; // 剪枝
path.push_back(candidates[i]);
back(candidates, i + 1, sum + candidates[i], target);
// 之前在递归前sum先加,递归后sum再减;但此次直接将表达式作为参数,并没有改变sum的值
path.pop_back();
while (i+1<candidates.size() && candidates[i+1] == candidates[i]) i++; // 跳过相同
}
}
};