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: vector<vector<string>> res; void backtrack(vector<string>& path,string& s, int start) { if (start == s.size()) { res.push_back(path); return; } for (int i = start; i < s.size(); ++i) { if (!isPalindrome(s,start,i)) { continue; } string ss = s.substr(start,i-start+1); path.push_back(ss); backtrack(path,s,i+1); path.pop_back(); } } bool isPalindrome(const string s,int start, int end) { for(int i = start,j = end; j>i;++i,--j) { if(s[i]!=s[j]) { return false; } } return true; } vector<vector<string>> partition(string s) { vector<string> path; backtrack(path,s,0); return res; } };
1 class Solution { 2 private List<List<String>> res = new ArrayList<>(); 3 public List<List<String>> partition(String s) { 4 5 help(new ArrayList<>(), s, 0); 6 return res; 7 } 8 9 private void help( List<String> temp, String s, int index){ 10 if(index == s.length()) 11 res.add(new ArrayList<>(temp)); 12 else{ 13 for(int i = index; i < s.length(); i++){ 14 if(isPalindrome(s, index, i)){ 15 temp.add(s.substring(index, i + 1)); 16 help(temp, s, i + 1); 17 temp.remove(temp.size() - 1); 18 } 19 } 20 } 21 } 22 23 public boolean isPalindrome(String s, int low, int high){ 24 while(low < high) 25 if(s.charAt(low++) != s.charAt(high--)) return false; 26 return true; 27 } 28 }