1, 组合总和
class Solution {
public:
void backtracking(vector
{
if(sum > target)
{
return;
}
if(sum == target)
{
ret.push_back(path);
return;
}
for(int i = start; 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
backtracking(candidates, target, 0, 0);
return ret;
}
private:
vector<vector
vector
};
-
组合总和II
class Solution {
public:
void backtracking(vector&candidates, int target, int sum, int start, vector &used)
{
if(sum > target)
{
return;
}
if(sum == target)
{
ret.push_back(path);
return;
}
for(int i = start; i < candidates.size(); ++i)
{
if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == 0)
{
continue;
}
used[i] = 1;
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates, target, sum, i+1, used);
sum -= candidates[i];
used[i] = 0;
path.pop_back();
}
}
vector<vector> combinationSum2(vector & candidates, int target) {
sort(candidates.begin(), candidates.end());
vectorused(candidates.size(), 0);
backtracking(candidates, target, 0, 0, used);
return ret;
}
private:
vector<vector> ret;
vectorpath;
}; -
分割回文串
class Solution {
public:
bool isPa(string s, int left, int right)
{
while(left < right)
{
if(s[left] != s[right])
{
return false;
}
left++;
right--;
}
return true;
}
void backtracking(string s, int start)
{
if(start == s.size())
{
ret.push_back(path);
return;
}
for(int i = start; i < s.size(); ++i)
{
if(isPa(s, start, i))
{
path.push_back(s.substr(start, i-start+1));
}
else
{
continue;
}
backtracking(s, i+1);
path.pop_back();
}
}
vector<vector
backtracking(s, 0);
return ret;
}
private:
vector
vector<vector
};