LeetCode131. 分割回文串
☆☆☆思路1:递归+回溯
思路2:动态规划。 M
class Solution { public List<List<String>> partition(String s) { List<List<String>> res = new ArrayList<>(); dfs(s, 0, new ArrayList<>(), res); return res; } private void dfs(String s, int start, List<String> list, List<List<String>> res) { if (start == s.length()) { res.add(new ArrayList<>(list)); return; } for (int i = start; i < s.length(); i++) { String temp = s.substring(start, i + 1); if (isPalindrome(temp)) { list.add(temp); dfs(s, i + 1, list, res); list.remove(list.size() - 1); } } } // 判断是否是回文串 private boolean isPalindrome(String s) { if (s == null || s.length() <= 1) return true; int left = 0, right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left ++; right --; } return true; } }