Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s ="aab",
Return
[ ["aa","b"], ["a","a","b"] ]
找出所有的情况,可以用DFS+回溯
bool ispalin(int start, int end, string s)
{
while (start<end)
{
if (s[start]!=s[end])
{
return false;
}
++start;
--end;
}
return true;
}
//DFS 回溯
void dfs(string s,vector<string>& nres,vector<vector<string>>& res,int pos,int length)
{
//chukou
if (pos >= length)
res.push_back(nres);
//从pos开始循环
for (int i = pos; i < length; ++i)
{
//确定一个范围
int left = pos;
int right = i;
if (ispalin(left,right,s))
{
nres.push_back(s.substr(pos, i - pos + 1));
dfs(s,nres,res,i+1,length);
nres.pop_back();//回溯还原
}
}
}
vector<vector<string>> partition(string s) {
vector<string> nres;
vector<vector<string>> res;
int len = s.length();
if (len == 0)
return res;
dfs(s, nres, res, 0, len);
return res;
}
找出最短的分割方法
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning ofs.
For example, given s ="aab",
Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.
肯定是动态规划咯 对于dp[i]表示以第i个字符结尾的最短分割次数,
状态转移方程为: dp[i] = 0 0-i为回文串
=min(dp[j-1]+1) 从j-i为回文串的情况
bool ispalin(int start, int end, string s)
{
while (start<end)
{
if (s[start]!=s[end])
{
return false;
}
++start;
--end;
}
return true;
}
int minCut(string s) {
int len = s.length();
if(len==0)
return 0;
int* dp = new int[len];
dp[0]=0;
for(int i=1;i<len;++i)
{
if(ispalin(0,i,s))
dp[i]=0;
else
dp[i]=i;
for(int j=1;j<=i;++j)
{
if(ispalin(j,i,s))
{
dp[i]=min(dp[i],dp[j-1]+1);
}
}
}
int res = dp[len-1];
delete[] dp;
return res;
}