回溯算法练习题
LeetCode链接:131. 分割回文串
1.题目描述
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
示例 1:
1 2
| 输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
|
示例 2:
提示:
1 <= s.length <= 16
s
仅由小写英文字母组成
2.题解
2.1 回溯
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { List<List<String>> result = new ArrayList<>(); List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) { backtracking(s, 0); return result; }
public void backtracking(String s, int start) { if (start == s.length()) { result.add(new ArrayList<>(path)); return; }
for (int i = start; i < s.length(); i++) { String sub = s.substring(start, i + 1); if (isPalindrome(sub)) { path.add(sub); backtracking(s, i + 1); path.remove(path.size() - 1); } } }
public boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } }
|
1.题目描述
给你一个字符串 s
,请你将 s
分割成一些子串,使每个子串都是回文串。返回符合要求的 最少分割次数 。
示例 1:
1 2 3
| 输入:s = "aab" 输出:1 解释:只需一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。
|
示例 2:
示例 3:
提示:
1 <= s.length <= 2000
s
仅由小写英文字母组成
2.题解
2.1 写法1-超时
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
| class Solution { int min = Integer.MAX_VALUE; List<String> path = new ArrayList<>();
public int minCut(String s) { backtracking(s,0); return min; }
public void backtracking(String s, int start) { if (start == s.length()) { min = path.size()-1 < min ? path.size()-1 : min; return; }
for (int i = start; i < s.length(); i++) { String sub = s.substring(start, i + 1); if (isPalindrome(sub)) { path.add(sub); backtracking(s, i + 1); path.remove(path.size() - 1); } } }
public boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) return false; left++; right--; } return true; } }
|