《LeetCode力扣练习》代码随想录——回溯算法(分割回文串—Java)
刷题思路来源于 代码随想录
131. 分割回文串
-
回溯
class Solution { private List<String> path = new ArrayList<>(); // private Deque<String> path = new LinkedList<>(); // private Deque<String> path = new ArrayDeque<>(); private List<List<String>> result = new ArrayList<>(); public List<List<String>> partition(String s) { backtrack(s, 0); return result; } private void backtrack(String s, int startIndex) { if (startIndex == s.length()) { result.add(new ArrayList<>(path)); return; } for (int i = startIndex; i < s.length(); i++) { if (!verify(s, startIndex, i)) { continue; } path.add(s.substring(startIndex, i + 1)); // path.offerLast(s.substring(startIndex, i + 1)); backtrack(s, i + 1); path.remove(path.size() - 1); // path.pollLast(); } return; } private boolean verify(String s, int left, int right) { while (left <= right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; } }