leetcode 131
思路:回溯
比如说aab,对于每个元素currentNum,有两种选择:
1.如果currentNum<len-1,可以将当前元素加入到currentStr中,然后dfs(start,currentNum+1)。而currentNum==len-1时不能dfs(start,currentNum+1),这样下一轮循环就执行以下代码了
if (currentNum == len){ans.add(new ArrayList<>(currentList));return;
}
会导致最后一个str丢失,并且结果会加入到ans中。
2.如果start到currentNum是回文串,可以取start到currentNum这一字串加到ans中,然后dfs(currentNum+1,currentNum+1)
代码:
class Solution {List<List<String>> ans = new ArrayList<>();public List<List<String>> partition(String s) {dfs(0, 0, s.length(), s, "", new ArrayList<>());return ans;}public void dfs(int startNum, int currentNum, int len, String s, String currentStr, List<String> currentList) {//每一位有两种选法,一种是加在上一个String里,另一种是新建Stringif (currentNum == len){ans.add(new ArrayList<>(currentList));return;}if (currentNum<len-1){dfs(startNum, currentNum + 1, len, s, currentStr, currentList);}//加在上一个string里if (isPalindrome(s, startNum, currentNum)) {currentList.add(s.substring(startNum, currentNum+1));dfs(currentNum + 1, currentNum + 1, len, s, currentStr, currentList);currentList.remove(currentList.size() - 1);}//}public boolean isPalindrome(String s, int left, int right) {while (left < right) {if (s.charAt(left) != s.charAt(right)) {return false;}left++;right--;}return true;}
}