Palindrome Partitioning
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"] ]
空间换时间。
使用二维数组isPalin记录每个子串是否为回文串。
然后递归来做。可以看做深度优先搜索。
class Solution { public: vector<vector<bool> > isPalin; // isPalin[i][j]==true means s[i,...,j] is palindrome void buildMap(string s) { int n = s.size(); isPalin.resize(n, vector<bool>(n, false)); for(int i = 0; i < n; i ++) isPalin[i][i] = true; for(int i = n-1; i >= 0; i --) { for(int j = i+1; j < n; j ++) { if(s[i] == s[j]) { if(j == i+1 || isPalin[i+1][j-1] == true) isPalin[i][j] = true; } } } } vector<vector<string>> partition(string s) { buildMap(s); vector<vector<string> > ret; vector<string> cur; Helper(ret, cur, s, 0); return ret; } void Helper(vector<vector<string> >& ret, vector<string> cur, string s, int offset) { if(s == "") ret.push_back(cur); for(int i = 0; i < s.size(); i ++) { if(isPalin[offset+0][offset+i] == true) { cur.push_back(s.substr(0, i+1)); //palin prefix Helper(ret, cur, s.substr(i+1), offset+i+1); cur.pop_back(); } } } };