39. 组合总和
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int sum=0;
void dfs(vector<int>& candidates, int target, int startIdx){
if(sum==target){
result.push_back(path);
return;
}
if(sum>target)
return;
for(int i=startIdx; i<candidates.size(); i++){
path.push_back(candidates[i]);
sum+=candidates[i];
dfs(candidates,target,i);
sum-=candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
dfs(candidates,target,0);
return result;
}
};
因为可以重复选取,所以递归的下一个数字的搜索起点(startIdx)是i,而非i+1。
40. 组合总和 II
class Solution {
public:
vector<vector<int>> result;
vector<int> path;
int sum=0;
void dfs(vector<int>& candidates, int target, int startIdx){
if(sum==target){
result.push_back(path);
return;
}
if(sum>target)
return;
for(int i=startIdx; i< candidates.size();i++){
path.push_back(candidates[i]);
sum+=candidates[i];
dfs(candidates,target,i+1);
sum-=candidates[i];
path.pop_back();
while(i+1<candidates.size()&&candidates[i+1]==candidates[i])
i++;
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
dfs(candidates,target,0);
return result;
}
};
回溯之后,相同数值的元素直接跳过,实现本层去重功能。
131. 分割回文串
class Solution {
public:
vector<vector<string>> result;
vector<string> path;
bool check(string& s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s[left++] != s[right--])
return false;
}
return true;
}
void dfs(string& s, int stardIdx) {
if (stardIdx == s.length()) {
result.push_back(path);
return;
}
for (int endIdx = stardIdx + 1; endIdx <= s.length(); endIdx++) {
string sub = s.substr(stardIdx, endIdx - stardIdx); //[startIdx,endIdx) 左闭右开
if (check(sub)) {
path.push_back(sub);
dfs(s, endIdx);
path.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
dfs(s, 0);
return result;
}
};
子串在合法的情况下,才会尝试递归新的起点位置(startIdx),直到已经切分到末尾,收集结果。
标签:return,target,23,int,随想录,vector,candidates,result,回溯 From: https://blog.csdn.net/jiyisuifeng1991/article/details/141914333