39- 组合总和
题目链接:LeetCode-39中等
思考:无重复元素,但能有重复元素的组合总和
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
backtracking(candidates,target,0,0);
return result;
}
private:
vector<vector<int>> result;
vector<int> path;
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);// 不用i+1了,表示可以重复读取当前的数
sum-=candidates[i];
path.pop_back();
}
}
};
40- 组合总和||
题目链接:LeetCode-40中等
思考:有重复元素,但还不能有重复的组合
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<bool> used(candidates.size(),false);
path.clear();
result.clear();
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0,used);
return result;
}
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates,int target,int sum,int startIndex, vector<bool>& used){
if(sum==target){
result.push_back(path);
result;
}
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();
}
}
};
131-分割回文串
题目链接:LeetCode-131中等
class Solution {
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s,0);
return result;
}
private:
vector<vector<string>> result;
vector<string> path;
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(isPalindrome(s,startIndex,i)){
string str=s.substr(startIndex,i-startIndex+1);
path.push_back(str);
}else{
continue;
}
backtracking(s,i+1);
path.pop_back();
}
}
bool isPalindrome(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;
}
};