|
1 | 1 | package backtracking;
|
2 | 2 |
|
3 |
| -import java.util.ArrayList; |
4 |
| -import java.util.Arrays; |
5 |
| -import java.util.List; |
| 3 | +import java.util.*; |
6 | 4 |
|
7 | 5 | // https://leetcode.com/problems/palindrome-partitioning/
|
8 | 6 | public class PalindromePartitioning {
|
9 | 7 |
|
10 | 8 | public static void main(String[] args) {
|
11 | 9 | String s = "aab";
|
12 | 10 | PalindromePartitioning obj = new PalindromePartitioning();
|
13 |
| - List<List<String>> resultList = obj.partition(s); |
| 11 | + //List<List<String>> resultList = obj.partition(s); |
| 12 | + List<List<String>> resultList = obj.partitionWithDP(s); |
14 | 13 | System.out.println(Arrays.toString(resultList.toArray()));
|
15 | 14 | }
|
16 | 15 |
|
@@ -53,4 +52,30 @@ private boolean isPal(String s, int l, int r) {
|
53 | 52 |
|
54 | 53 | return true;
|
55 | 54 | }
|
| 55 | + |
| 56 | + public List<List<String>> partitionWithDP(String s) { |
| 57 | + int len = s.length(); |
| 58 | + List<List<String>>[] results = new List[len + 1]; |
| 59 | + results[0] = new ArrayList<List<String>>(); |
| 60 | + results[0].add(new ArrayList<String>()); |
| 61 | + |
| 62 | + boolean[][] pair = new boolean[len][len]; |
| 63 | + for (int i = 0; i < len; i++) { |
| 64 | + results[i + 1] = new ArrayList<List<String>>(); |
| 65 | + for (int left = 0; left <= i; left++) { |
| 66 | + if (s.charAt(left) == s.charAt(i) && (i-left <= 1 || pair[left + 1][i - 1])) { |
| 67 | + pair[left][i] = true; |
| 68 | + String sub = s.substring(left, i + 1); |
| 69 | + for (List<String> list: results[left]) { |
| 70 | + List<String> newList = new ArrayList<String>(list); |
| 71 | + newList.add(sub); |
| 72 | + results[i + 1].add(newList); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + } |
| 78 | + |
| 79 | + return results[len]; |
| 80 | + } |
56 | 81 | }
|
0 commit comments