Leetcode, PalindromePartitioning
solution2参考Subsets2
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isPalindrome(string s, int start, int end)
{
while ( start < end && s[start] == s[end] )
{
++start;
--end;
}
return start >= end;
}
void dfs( string s, vector<string> &path, vector<vector<string>> &res,
int prev, int start)
{
//最后一个隔板
if ( start == s.size() )
{
if (isPalindrome(s, prev, start - 1))
{
path.push_back(s.substr(prev, start - prev) );
res.push_back(path);
path.pop_back();
}
return;
}
//不断开
dfs(s, path, res, prev, start + 1);
//如果[prev, start - 1]是回文,可断开,也可以不断开(上一层已经做了)
if ( isPalindrome(s, prev, start - 1))
{
//断开
path.push_back(s.substr(prev, start - prev));
dfs(s, path, res, start, start + 1);
path.pop_back();
}
}
//时间复杂度O(2^n),空间复杂度O(n)
vector<vector<string>> solution(string s)
{
vector<vector<string>> res;
vector<string> path;
dfs(s, path, res, 0, 1);
return res;
}
void dfs2(string s, vector<string> &path, vector<vector<string>> &res, int start)
{
if (start == s.size())
{
res.push_back(path);
return;
}
for ( int i = start; i < s.size(); ++i )
{
if (isPalindrome(s, start, i))
{
//断开
path.push_back(s.substr(start, i - start + 1));
dfs2(s, path, res, i + 1);
path.pop_back();
}
}
}
//时间复杂度O(2^n),空间复杂度O(n)
vector<vector<string>> solution2(string s)
{
vector<vector<string>> res;
vector<string> path;
dfs2(s, path, res, 0);
return res;
}
int main()
{
string s = "aab";
//auto res = solution(s);
auto res = solution2(s);
//auto res = solution3(s);
#if 0
{
["a", "a", "b"],
["aa", "b"]
}
#endif // 0
return 0;
}
//动规
vector<vector<string>> solution3(string s)
{
const int n = s.size();
vector<vector<bool>> p(n, vector<bool>(n, false));
for ( int i = n - 1; i >= 0; --i )
{
for ( int j = i; j < n; ++j )
{
p[i][j] = s[i] == s[j] && ( (j - i < 2) || p[i + 1][j - 1] );
}
}
vector<vector<vector<string>>> sub_palins(n);
for (int i = n - 1; i >= 0; --i)
{
for (int j = i; j < n; ++j)
{
if ( p[i][j] )
{
const string palindrome = s.substr(i, j - i + 1);
if ( j + 1 < n )
{
for ( auto v : sub_palins[j + 1] )
{
v.insert(v.begin(), palindrome);
sub_palins[i].push_back(v);
}
}
else
{
sub_palins[i].push_back(vector<string>{palindrome});
}
}
}
}
return sub_palins[0];
}