Title
Given A string s, partition s such that every substring of the partition are a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["AA", "B"], ["A", "a", "B"] ]
Test instructions
Given a string s, the division of S is required, and each substring is a palindrome string.
Request to return the entire division situation
Ideas
The intuitive idea is to use layered recursion. First point is determined first. Then determine the second point, then determine the third point, and so on. The time complexity of such a method is very high.
The subject uses DP: First calculate the random two position i,j between the string is a palindrome string, with ispalindrome[i][j] expression.
Code
Class Solution {Public:void getpartition (vector<vector<string> >&result, vector<string>& Splits, int start, string&s, vector<vector<bool> >&ispal) {//spits-A segmented result, start-where the current slice started 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.pus H_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)); Initialize the ispal[i][i]=true; for (int i=0; i<len; i++) Ispal[i][i]=true; Initializes a substring of the adjacent two-character string for (int i=0; i<len-1; i++) if (s[i]==s[i+1]) ispal[i][i+1]=true; Infer the location of other 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]; Determine all combinations of vector<string> splits; Getpartition (result, splits, 0, S, ispal); return result; }};
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Leetcode:palindrome partitioning [131]