Skip to content

Commit 3ac5ff2

Browse files
committed
dp solution for palindrome partitioning
1 parent 04e2c00 commit 3ac5ff2

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

code/LeetCode/src/backtracking/PalindromePartitioning.java

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
package backtracking;
22

3-
import java.util.ArrayList;
4-
import java.util.Arrays;
5-
import java.util.List;
3+
import java.util.*;
64

75
// https://leetcode.com/problems/palindrome-partitioning/
86
public class PalindromePartitioning {
97

108
public static void main(String[] args) {
119
String s = "aab";
1210
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);
1413
System.out.println(Arrays.toString(resultList.toArray()));
1514
}
1615

@@ -53,4 +52,30 @@ private boolean isPal(String s, int l, int r) {
5352

5453
return true;
5554
}
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+
}
5681
}

0 commit comments

Comments
 (0)