131-分割回文串

131-分割回文串

力扣131

https://leetcode-cn.com/problems/palindrome-partitioning/

回溯问题,一开始看到样例的结果是单个的在最后面,导致想复杂了

贴完整代码

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
37
38
39
public class one_three_one_分割回文串 {

@Test
public void test(){
String s = "";
partition(s);
System.out.println(res.toString());
}

private List<List<String>> res = new ArrayList<>();

public List<List<String>> partition(String s) {
backtrace(s, new ArrayList<>(), 0);
return res;
}

public void backtrace(String s, List<String> path, int splitIndex){
if (splitIndex == s.length()){ //结束条件:分割到底
res.add(new ArrayList<>(path));
return ;
}
for (int i = splitIndex; i < s.length(); i++) {
String a = s.substring(splitIndex, i + 1); //做选择
path.add(a);
if (check(a)){ //条件递归
backtrace(s, path, i + 1);
}
path.remove(path.size() - 1); //撤销选择
}
}

//检验回文
public boolean check(String str){
for (int i = 0; i < str.length() / 2; i++) {
if (str.charAt(i) != str.charAt(str.length() - i - 1)) return false;
}
return true;
}
}

13ms


剪枝:将判断添加在add(做选择前),可以减少多次add remove操作,提升到5-8ms

其他不变,只贴有变动的backtrace函数

1
2
3
4
5
6
7
8
9
10
11
12
13
public void backtrace(String s, List<String> path, int splitIndex){
if (splitIndex == s.length()){
res.add(new ArrayList<>(path));
return ;
}
for (int i = splitIndex; i < s.length(); i++) {
String a = s.substring(splitIndex, i + 1);
if (!check(a)) continue; //先判断不回文,减少一次add和remove操作
path.add(a);
backtrace(s, path, i + 1);
path.remove(path.size() - 1);
}
}

其他回溯的题目可以点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×