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"] ]
class Solution { public: void getPartition(vector<vector<string> >&result, vector<string>&splits, int start, string&s, vector<vector<bool> >&isPal){ //spits-已切分的结果,start-当前切分开始的位置 if(start==s.length()){ vector<string> newSplits = splits; result.push_back(newSplits); return; } for(int end=start; end<s.length(); end++){ if(isPal[start][end]){ splits.push_back(s.substr(start, end-start+1)); getPartition(result, splits, end+1, s, isPal); splits.pop_back(); } } } vector<vector<string>> partition(string s) { vector<vector<string> >result; int len=s.length(); if(len==0)return result; vector<vector<bool> > isPal(len, vector<bool>(len, false)); //初始化isPal[i][i]=true; for(int i=0; i<len; i++) isPal[i][i]=true; //初始化相邻两位字符构成的子串 for(int i=0; i<len-1; i++) if(s[i]==s[i+1])isPal[i][i+1]=true; //判断其他i<j的位置 for(int i=len-3; i>=0; i--) for(int j=i+2; j<len; j++) isPal[i][j]=(s[i]==s[j]) && isPal[i+1][j-1]; //确定所有的组合 vector<string> splits; getPartition(result, splits, 0, s, isPal); return result; } };
LeetCode: Palindrome Partitioning [131],布布扣,bubuko.com
LeetCode: Palindrome Partitioning [131]
原文:http://blog.csdn.net/harryhuang1990/article/details/34423001