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"] ]
填写dp矩阵的时候坐标弄反了浪费了好多时间……
class Solution { public: vector<vector <int> >dp; vector<vector<string>> re; int len; vector<vector<string>> partition(string s) { string ss =""; if(s.size() == 0)return re; if(s.size()==1) { vector<string> tp ; tp.push_back(s); re.push_back(tp); return re; } ss = ss+s[0]; for(int i = 1 ; i < s.length();i++) { ss = ss + "#"; ss = ss + s[i]; } len = ss.size(); for(int i = 0 ; i < len ;i++) { vector<int> tp(len,0); dp.push_back(tp); } for(int i = 0 ; i < len ; i++) dp[i][i] = 1; for(int i = 0 ; i < len ;i++) { int j = 1; while(i-j>=0 && i+j<len && ss[i-j] == ss[i+j]) { dp[i-j][i+j] = 1; j++; } } vector<string> temp; fill(0,temp,s); return re; } void fill(int n, vector<string> now,string s) { if(n >= len) { re.push_back(now); return; } for(int i = n ; i < len ;i++) { if(dp[n][i] == 1) { if(n%2 == 0) { string sub =s.substr(n/2,i/2-n/2+1); if(sub == "")continue; now.push_back(sub); } else { string sub =s.substr((n+1)/2,(i+1)/2-(n+1)/2); if(sub == "")continue; now.push_back(sub); } fill(i+2,now,s); now.pop_back(); } } } };
posted on 2014-04-15 16:48 pengyu2003 阅读(110) 评论(0) 编辑 收藏 举报