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"]
]
- public class Solution {
- public List<List<String>> partition(String s) {
- ArrayList<List<String>> res = new ArrayList<List<String>>();
- if(s.length()==0) return res;
- boolean flag[][] = new boolean[s.length()][s.length()];
- for(int i=0;i<s.length();i++){
- flag[i][i] = true;
- }
- for(int i=s.length()-1;i>=0;i--){
- for(int j=i+1;j<s.length();j++){
- if(s.charAt(i)==s.charAt(j)){
- if(j-i==1){
- flag[i][j] = true;
- }else{
- flag[i][j] = flag[i+1][j-1];
- }
- }else{
- flag[i][j] = false;
- }
- }
- }
- dfs(res, flag, new ArrayList<String>(), 0, s);
- return res;
- }
-
- void dfs(ArrayList<List<String>> res,boolean[][] flag,List<String> item,int start,String s){
- if(start==flag.length){
- res.add(new ArrayList<String>(item));
- }else{
- for(int i=start+1;i<flag.length+1;i++){
- if(flag[start][i-1]){
- item.add(s.substring(start, i));
- dfs(res, flag, item, i, s);
- item.remove(item.size()-1);
- }
- }
- }
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46554255