Leetcode(131) Palindrome Partitioning

Description

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

1
2
3
4
5
6
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

解法

经验:遇到要求所有组合、可能、排列等解集的题目,一般都是DFS + backtracking

  • 首先传入s=”aab” path=[] res = [], 首先切割出”a”(然后是”aa” “aab” …),然后判读它是不是回文串:
  • 如果不是,直接跳过
  • 如果是,则此时剩余的 s=”ab”, path += [“a”]
  • 写入res的判断是,当s=””时,记录结果

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
List<List<String>> res = new ArrayList<>();
public List<List<String>> partition(String s) {
List<String> path = new ArrayList<>();
helper(s, path);
return res;
}
void helper(String s, List<String> path){
if(s.equals("")){
if(path.size()!=0){
List<String> respath = new ArrayList<>(path);
res.add(respath);
}
return;
}
for(int i = 0; i <= s.length(); i++){
if(judge(s.substring(0,i))){
path.add(s.substring(0,i));
helper(s.substring(i),path);
path.remove(path.size() - 1);
}
}

}
Boolean judge(String s){
if(s.length() == 0){
return false;
}
for(int i = 0 ; i < s.length(); i++){
if(s.charAt(i) != s.charAt(s.length() - i - 1)){
return false;
}
}
return true;
}
}