题目链接:39. 组合总和
本题和77.组合 (opens new window)、216.组合总和III (opens new window)的一个区别是:本题元素为可重复选取的。
代码如下:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backTacking(vector<int>& candidates,int sum, int target,int startIndex)
{
if(sum==target)
{
result.push_back(path);
return;
}
for(int i=startIndex;i < candidates.size() && sum + candidates[i] <= target;i++)
{
sum+=candidates[i];
path.push_back(candidates[i]);
backTacking(candidates,sum,target,i);
sum-=candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
result.clear();
path.clear();
sort(candidates.begin(),candidates.end());
backTacking(candidates,0,target,0);
return result;
}
};
题目链接:40.组合总和II
candidates 中的每个数字在每个组合中只能使用 一次 且解集不能包含重复的组合,故需要加上以下约束条件。
if(i >0&& candidates[i]== candidates[i -1]&& used[i -1]==false)
{
continue;
}
整体代码如下:
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backTacking(vector<int>& candidates, int target,int sum,int startIndex)
{
if(sum==target)
{
result.push_back(path);
return;
}
for(int i=startIndex;i<candidates.size()&&sum+candidates[i]<=target;i++)
{
if(i>startIndex&&candidates[i]==candidates[i-1])
continue;
sum+=candidates[i];
path.push_back(candidates[i]);
//used[i]=true;
backTacking(candidates,target,sum,i+1);
//used[i]=false;
sum-=candidates[i];
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
// vector<bool> used(candidates.size(),false);
result.clear();
path.clear();
sort(candidates.begin(),candidates.end());
backTacking(candidates,target,0,0);
return result;
}
};
题目链接:131.分割回文串
class Solution {
private:
vector<vector<string>> result;
vector<string> path;
vector<vector<bool>> isPalindrom;
void backTacking(string& s,int startIndex)
{
if(startIndex>=s.size())
{
result.push_back(path);
return;
}
for(int i=startIndex;i<s.size();i++)
{
if(isPalindrom[startIndex][i])
{
string str=s.substr(startIndex,i-startIndex+1);
path.push_back(str);
}
else
continue;
backTacking(s,i+1);
path.pop_back();
}
}
void computePalindrom(string& s)
{
isPalindrom.resize(s.size(),vector<bool>(s.size(),false));
for(int i=s.size()-1;i>=0;i--)
for(int j=i;j<s.size();j++)
{
if(j==i) isPalindrom[i][j]=true;
else if(j-i==1) isPalindrom[i][j]=(s[i]==s[j]);
else isPalindrom[i][j]=(s[i]==s[j]&&isPalindrom[i+1][j-1]);
// else {isPalindrom[i][j] = (s[i] == s[j] && isPalindrom[i+1][j-1]);}
}
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
computePalindrom(s);
backTacking(s,0);
return result;
}
};