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"] ]Analysis:
return all possible palindrome partitioning of s, remind us using DFS.
Java
public class Solution {
List<List<String>> result;
List<String> solu;
public List<List<String>> partition(String s) {
result = new ArrayList<>();
solu = new ArrayList<>();
getPalindrome(s, 0);
return result;
}
public void getPalindrome(String s, int start){
if(start==s.length()){
result.add(new ArrayList<>(solu));
return;
}
for(int i=start;i<s.length();i++){
if(isPalindrome(s.substring(start, i+1))){
solu.add(s.substring(start, i+1));
getPalindrome(s, i+1);
solu.remove(solu.size()-1);
}
}
}
public boolean isPalindrome(String s){
if(s.length()<=1) return true;
int len = s.length();
for(int i=0;i<len;i++){
if(s.charAt(i)!=s.charAt(len-1-i))
return false;
}
return true;
}
}
c++
class Solution {
public:
bool isPalindrome(string &s, int start, int end){
while(start < end){
if(s[start] != s[end])
return false;
start++, end--;
}
return true;
}
void DFSPalin(vector<vector<string>> &result,
vector<string> solu,
string &s,
int start){
if(start == s.size()){
result.push_back(solu);
return;
}
for(int i= start; i<s.size();i++){
if(isPalindrome(s,start,i)){
solu.push_back(s.substr(start,i-start+1));
DFSPalin(result,solu,s,i+1);
solu.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> solution;
DFSPalin(result,solution,s,0);
return result;
}
};