leetcode--Palindrome Partitioning

来源:互联网 发布:python hmmlearn库 编辑:程序博客网 时间:2024/05/29 09:04

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"]  ]
[java] view plain copy
  1. public class Solution {  
  2.     public List<List<String>> partition(String s) {  
  3.         ArrayList<List<String>> res = new ArrayList<List<String>>();  
  4.         if(s.length()==0return res;  
  5.         boolean flag[][] = new boolean[s.length()][s.length()];  
  6.         for(int i=0;i<s.length();i++){  
  7.             flag[i][i] = true;  
  8.         }  
  9.         for(int i=s.length()-1;i>=0;i--){  
  10.             for(int j=i+1;j<s.length();j++){               
  11.                 if(s.charAt(i)==s.charAt(j)){  
  12.                     if(j-i==1){                       
  13.                         flag[i][j] = true;  
  14.                     }else{  
  15.                         flag[i][j] = flag[i+1][j-1];  
  16.                     }  
  17.                 }else{  
  18.                     flag[i][j] = false;  
  19.                 }  
  20.             }  
  21.         }         
  22.         dfs(res, flag, new ArrayList<String>(), 0, s);  
  23.         return res;  
  24.     }  
  25.       
  26.     void dfs(ArrayList<List<String>> res,boolean[][] flag,List<String> item,int start,String s){  
  27.         if(start==flag.length){  
  28.             res.add(new ArrayList<String>(item));  
  29.         }else{  
  30.             for(int i=start+1;i<flag.length+1;i++){  
  31.                 if(flag[start][i-1]){  
  32.                     item.add(s.substring(start, i));  
  33.                     dfs(res, flag, item, i, s);  
  34.                     item.remove(item.size()-1);  
  35.                 }  
  36.             }  
  37.         }  
  38.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46554255

原创粉丝点击