题目链接/文章讲解:https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html
视频讲解:https://www.bilibili.com/video/BV1KT4y1M7HJ
题目要求 同一个数字可以无限制重复被选取,代码改动的地方:backtracking(candidates,target,sum,i);(当前i可以重复出现)
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int sum=0;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex)
{
if(sum > target)
return;
if(sum == target)
{
result.push_back(path);
return;
}
for(int i=startIndex;i<candidates.size();i++)
{
sum+=candidates[i];
path.push_back(candidates[i]);
backtracking(candidates,target,sum,i);
sum-=candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtracking(candidates,target,0,0);
return result;
}
};
题目链接/文章讲解:https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html
视频讲解:https://www.bilibili.com/video/BV12V4y1V73A
考虑组合重复问题,设置了bool类型的used数组来记录状态
——对节点处理、回溯的时候,也要加上对used的更新
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int sum=0;
void backtracking(vector<int>& candidates,int target,int sum,int startIndex,vector<bool>& used){
if(sum == target)
{
result.push_back(path);
return;
}
//for循环的判断条件也修改了
for(int i=startIndex;i<candidates.size() && sum+candidates[i]<=target;i++)
{
//遇到重复元素直接跳过
if(i>0 && candidates[i]==candidates[i-1] && used[i-1] == false)
continue;
//下面是正常的处理节点的操作
sum+=candidates[i];
path.push_back(candidates[i]);
//加进去之后更新状态
used[i] = true;
backtracking(candidates,target,sum,i+1,used);
//回溯
used[i]=false;
sum-=candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(),false);
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,sum,0,used);
return result;
}
};
https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html
视频讲解:https://www.bilibili.com/video/BV1c54y1e7k6
这个题还是参考了代码,要着重复习一下。
class Solution {
public:
vector<vector<string>> result;
vector<string> path;
bool isHuiwen(const string& s,int start,int end)
{
for(int i=start,j=end;i<j;i++,j--)
{
if(s[i]!=s[j])
return false;
}
return true;
}
void backtracking(const string& s,int startIndex)
{
if(startIndex >= s.size()){
result.push_back(path);
return;
}
for(int i=startIndex;i<s.size();i++)
{
if(isHuiwen(s,startIndex,i)){
string str = s.substr(startIndex, i-startIndex+1);
path.push_back(str);
}else{
continue;
}
backtracking(s,i+1);
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
backtracking(s,0);
return result;
}
};