赞
踩
题目描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
代码
class Solution {
public:
int sum = 0;
vector<vector<int>> res;
vector<int> path;
void backTracking(vector<int>& candidates,int target,int startIndex) {
if (sum > target)
return;
if (sum == target) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backTracking(candidates, target,i);
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if (candidates.size() == 0) return res;
backTracking(candidates, target,0);
return res;
}
};
剪枝
上个代码对于sum已经大于target的情况,其实是依然进入了下一层递归,
只是下一层递归结束判断的时候,会判断sum > target的话就返回。
对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。
class Solution {
public:
int sum = 0;
vector<vector<int>> res;
vector<int> path;
void backTracking(vector<int>& candidates, int target, int startIndex) {
if (sum > target)
return;
if (sum == target) {
res.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum+candidates[i]<=target; i++) {
sum += candidates[i];
path.push_back(candidates[i]);
backTracking(candidates, target, i);
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
if (candidates.size() == 0) return res;
sort(candidates.begin(), candidates.end());
backTracking(candidates, target, 0);
return res;
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。