|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.List; |
| 5 | + |
| 6 | +publicclassPalindromePartitioning { |
| 7 | + |
| 8 | + |
| 9 | +publicList<List<String>>partition(Strings) { |
| 10 | +List<List<String>>result =newArrayList(); |
| 11 | +intn =s.length(); |
| 12 | +boolean[][]dp =newboolean[n][n]; |
| 13 | +for(inti =0;i <n;i++){ |
| 14 | +for(intj =0;j <=i;j++){ |
| 15 | +if(s.charAt(j) ==s.charAt(i) && (j+1 >=i-1 ||dp[j+1][i-1])){// j+1 >= i-1 means j and i are adjance to each other or only one char apart from each other |
| 16 | +//dp[j+1][i-1] means its inner substring is a palindrome, so as long as s.charAt(j) == s.charAt(i), then dp[j][i] must be a palindrome. |
| 17 | +dp[j][i] =true; |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | +for(boolean[]list :dp){ |
| 23 | +for(booleanb :list){ |
| 24 | +System.out.print(b +", "); |
| 25 | + } |
| 26 | +System.out.println(); |
| 27 | + } |
| 28 | +System.out.println(); |
| 29 | + |
| 30 | +backtracking(s,0,dp,newArrayList(),result); |
| 31 | + |
| 32 | +returnresult; |
| 33 | + } |
| 34 | + |
| 35 | +voidbacktracking(Strings,intstart,boolean[][]dp,List<String>temp, |
| 36 | +List<List<String>>result) { |
| 37 | +if (start ==s.length()) { |
| 38 | +List<String>newTemp =newArrayList(temp); |
| 39 | +result.add(newTemp); |
| 40 | + } |
| 41 | +for (inti =start;i <s.length();i++) { |
| 42 | +if (dp[start][i]) { |
| 43 | +temp.add(s.substring(start,i +1)); |
| 44 | +backtracking(s,i +1,dp,temp,result); |
| 45 | +temp.remove(temp.size() -1); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | +publicstaticvoidmain(String...strings){ |
| 52 | +PalindromePartitioningtest =newPalindromePartitioning(); |
| 53 | +Strings ="aab"; |
| 54 | +List<List<String>>result =test.partition(s); |
| 55 | +for(List<String>list :result){ |
| 56 | +for(Stringstr :list){ |
| 57 | +System.out.print(str +", "); |
| 58 | + } |
| 59 | +System.out.println(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |