(Version 0.0)

这题的思路比较straightforward,可以看出会有overlapping的子问题,因此可以先按DP做法用一个二维数组存储对于某一substring是不是palindrome的判断,然后做backtracking时可以利用这个DP二维数组的结果来跳过重复的palindrome判断,不过如果不想使用DP做法其实每次都重复判断是否某一substring是palindrome也是可以过OJ的。用DP预处理的做法代码如下:

 1 public class Solution {
 2     public List<List<String>> partition(String s) {
 3         List<List<String>> result = new ArrayList<>();
 4         boolean[][] isPalindrome = new boolean[s.length()][s.length()];
 5         for (int i = 0; i < isPalindrome.length; i++) {
 6             isPalindrome[i][i] = true;
 7         }
 8         for (int l = 2; l <= s.length(); l++) {
 9             for (int i = 0; i + l <= s.length(); i++) {
10                 int j = i + l - 1;
11                 isPalindrome[i][j] = (isPalindrome[i + 1][j - 1] || l == 2) && s.charAt(i) == s.charAt(j);
12             }
13         }
14         List<String> list = new ArrayList<>();
15         helper(result, list, s, isPalindrome, 0);
16         return result;
17     }
18     
19     private void helper(List<List<String>> result, List<String> list, String s, boolean[][] isPalindrome, int start) {
20         if (start == s.length()) {
21             List<String> temp = new ArrayList<>(list);
22             result.add(temp);
23             return;
24         }
25         for (int end = start; end < s.length(); end++) {
26             if (isPalindrome[start][end]) {
27                 list.add(s.substring(start, end + 1));
28                 helper(result, list, s, isPalindrome, end + 1);
29                 list.remove(list.size() - 1);
30             }
31         }
32     }
33 }

 

posted on 2015-03-12 10:18  _icecream  阅读(349)  评论(0编辑  收藏  举报