39. 组合总和
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。 candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1: 输入:candidates = [2,3,6,7], target = 7 输出:[[2,2,3],[7]] 解释: 2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。 7 也是一个候选, 7 = 7 。 仅有这两种组合。 示例 2: 输入: candidates = [2,3,5], target = 8 输出: [[2,2,2,2],[2,3,3],[3,5]] 示例 3: 输入: candidates = [2], target = 1 输出: []
提示:
- 1 <= candidates.length <= 30
- 2 <= candidates[i] <= 40
- candidates 的所有元素 互不相同
- 1 <= target <= 40
思路
仍然是经典组合问题,只需要修改一下递归的返回条件和start
题解
class Solution {
private:
vector<vector<int>> result;
vector<int> current;
int sum(vector<int>& nums) {
int s = 0;
for (int num : nums) {
s += num;
}
return s;
}
public:
void backtracking(vector<int>& candidates, int target, int start) {
if (sum(current) == target) {
result.push_back(current);
return;
}
if (sum(current) > target) {
return;
}
for (int i = start; i < candidates.size(); ++i) {
current.push_back(candidates[i]);
backtracking(candidates, target, i); // 注意这里是 i,因为数字可以重复使用
current.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates, target, 0);
return result;
}
};
40. 组合总和 II
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用 一次 。 注意:解集不能包含重复的组合。
示例 1: 输入: candidates = [10,1,2,7,6,1,5], target = 8, 输出: [ [1,1,6], [1,2,5], [1,7], [2,6] ] 示例 2: 输入: candidates = [2,5,2,1,2], target = 5, 输出: [ [1,2,2], [5] ]
提示:
- 1 <= candidates.length <= 100
- 1 <= candidates[i] <= 50
- 1 <= target <= 30
思路
这个问题与之前的问题非常相似,但有两个关键的不同之处:
- 每个数字在每个组合中只能使用一次。
- 解集不能包含重复的组合。
为了解决这两个问题,我们可以使用以下策略:
- 排序:首先对 candidates 进行排序,这样更容易避免重复组合。
- 回溯时跳过重复元素:在回溯过程中,如果发现与前一个元素相同的元素,就跳过它。
- 递归时改变开始索引:每次递归调用时,都从 candidates 的下一个元素开始,而不是当前元素。
题解
class Solution {
private:
vector<vector<int>> result;
vector<int> current;
void backtracking(vector<int>& candidates, int target, int start) {
if (target == 0) {
result.push_back(current);
return;
}
if (target < 0) {
return;
}
for (int i = start; i < candidates.size(); ++i) {
// 跳过重复元素
if (i > start && candidates[i] == candidates[i - 1]) continue;
current.push_back(candidates[i]);
// 递归调用时,将开始索引设置为下一个元素,避免重复使用
backtracking(candidates, target - candidates[i], i + 1);
current.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); // 对数组进行排序
backtracking(candidates, target, 0);
return result;
}
};