力扣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; path.add(a); backtrace(s, path, i + 1); path.remove(path.size() - 1); } }
|
其他回溯的题目可以点击这里