39. 组合总和
题目链接/文章讲解:链接地址
视频讲解:链接地址
代码思路:传入的参数:传入的参数每层需要遍历的元素,目标值,和值,开始的索引。
递归结束条件:sum 等于target
递归遍历:从startIndex开始,因为可以重复取元素,所以传入递归的索引是i, 而不是i + 1.
cpp
class Solution {
private:
vector<int> path;
vector<vector<int>> result;
void backtraking(vector<int>& condidates, int target, int sum, int startIndex) {
//结束条件
if (sum > target) return;
if (sum == target) {
result.push_back(path);
return;
};
for (int i = startIndex; i < condidates.size(); i++) {
sum += condidates[i];
path.push_back(condidates[i]);
backtraking(condidates, target, sum, i);
sum -= condidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtraking(candidates, target, 0 , 0);
return result;
}
};
40.组合总和II
题目链接/文章讲解:链接地址
视频讲解:链接地址
代码思路:注意需要保证每层没有重复使用的元素。
cpp
class Solution {
vector<int> path;
vector<vector<int>> result;
private:
void backtraking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {
if (sum == target) {
result.push_back(path);
return;
}
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
//同层不能使用重复元素
if (i > 0 && candidates[i - 1] == candidates[i] && used[i - 1] == false) {
continue;
}
sum += candidates[i];
path.push_back(candidates[i]);
used[i] = true;
backtraking(candidates, target, sum, i + 1, used);
sum -= candidates[i];
path.pop_back();
used[i] = false;
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backtraking(candidates, target, 0, 0, used);
return result;
}
};
131.分割回文串
题目链接/文章讲解:链接地址
视频讲解:链接地址
代码思路:这题比较难,暂时理解思路,打基础。