回溯解法,java:
public final List<List<String>> partition(String s) { List<List<String>> reList = new LinkedList<List<String>>(); partition(s, 0, new Stack<String>(), reList); return reList; } private final void partition(String s, int point, Stack<String> stack, List<List<String>> reList) { if (point >= s.length()) { reList.add(new ArrayList<String>(stack)); return; } for (int end = point + 1; end <= s.length(); end++) { String inStr = s.substring(point, end); if (!isalindrome(inStr)) { continue; } stack.push(inStr); partition(s, end, stack, reList); stack.pop(); } } private final boolean isalindrome(String s) { int left = 0; int right = s.length() - 1; while (left < right) { if (s.charAt(left) != s.charAt(right)) { return false; } left++; right--; } return true; }
回溯解法,javascript:
function isAlin(s) { let begin = 0; let end = s.length - 1; while (begin < end) { if (s.charAt(begin) != s.charAt(end)) { return false; } begin++; end--; } return true; } function findPalidrome(s, begin, stack, reList) { if (begin == s.length) { reList.push(stack.slice()); return; } for (let i = begin + 1; i <= s.length; i++) { let sIn = s.slice(begin, i); if (!isAlin(sIn)) { continue; } stack.push(sIn); findPalidrome(s, i, stack, reList); stack.pop(); } } var partition = function(s) { let reList = []; findPalidrome(s,0,[],reList); return reList }