1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Jan 20, 2015
4
+ Problem: Palindrome Partitioning
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/palindrome-partitioning/
7
+ Notes:
8
+ Given a string s, partition s such that every substring of the partition is a palindrome.
9
+ Return all possible palindrome partitioning of s.
10
+ For example, given s = "aab",
11
+ Return
12
+ [
13
+ ["aa","b"],
14
+ ["a","a","b"]
15
+ ]
16
+
17
+ Solution: ...
18
+ */
19
+
20
+ public class Solution {
21
+ public List <List <String >> partition (String s ) {
22
+ List <List <String >> res = new ArrayList <List <String >>();
23
+ int n = s .length ();
24
+ boolean [][] dp = new boolean [n ][n ];
25
+ for (int i = n - 1 ; i >= 0 ; --i ) {
26
+ for (int j = i ; j < n ; ++j ) {
27
+ dp [i ][j ]=(s .charAt (i )==s .charAt (j ))&&(j <i +2 ||dp [i +1 ][j -1 ]);
28
+ }
29
+ }
30
+ ArrayList <String > path = new ArrayList <String >();
31
+ dfs (s , dp , 0 , path , res );
32
+ return res ;
33
+ }
34
+ public void dfs (String s , boolean [][] dp , int start , ArrayList <String > path , List <List <String >> res ) {
35
+ if (s .length () == start ) {
36
+ res .add (new ArrayList <String >(path ));
37
+ return ;
38
+ }
39
+ for (int i = start ; i < s .length (); ++i ) {
40
+ if (dp [start ][i ] == false ) continue ;
41
+ path .add (s .substring (start ,i +1 ));
42
+ dfs (s , dp , i +1 ,path ,res );
43
+ path .remove (path .size ()-1 );
44
+ }
45
+ }
46
+ }
0 commit comments