Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
总结见:http://www.jianshu.com/p/883fdda93a66
Solution1:Backtracking(DFS),
思路:回溯法,从start到n 取i开始测试substr(start, i)是否为回文,如果是的话,再DFS继续测试substr(start=i, next_i)是否回文,递归继续。到底后或者发现不是,step back by removing回溯到上一步, i=i+1,继续测试substr(start, i)。
回溯顺序:
输入abcdef
测试a, b, c, d, e
测试ab, 如是继续测c, cd, cde..
测试abc,如是继续测c, cd, cde...
Time Complexity: O(2^N *N): 2^N组合次数(每个字符可以cut or not),and isPalindrome function is O(n)
Space Complexity(不算result的话): O(2n) : n是递归缓存的cur_result + n是缓存了n层的普通变量O(1) ? (Not Sure)
Solution1.2:Backtracking(DFS) Round1
Solution1 Code:
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
List<String> cur_res = new ArrayList<>();
backtrack(s, 0, cur_res, result);
return result;
}
public void backtrack(String s, int start, List<String> cur_res, List<List<String>> result) {
if(start == s.length()) {
result.add(new ArrayList<>(cur_res));
}
for(int i = start; i < s.length(); i++) {
if(!isPalindrome(s, start, i)) {
continue;
}
cur_res.add(s.substring(start, i + 1));
backtrack(s, i + 1, cur_res, result);
cur_res.remove(cur_res.size() - 1);
}
}
public boolean isPalindrome(String s, int low, int high){
while(low < high)
if(s.charAt(low++) != s.charAt(high--)) return false;
return true;
}
}
Solution1.2 Round1 Code:
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
if(s == null || s.length() == 0) {
return result;
}
List<String> cur_res = new ArrayList<>();
backtrack(s, 0, cur_res, result);
return result;
}
private void backtrack(String s, int start, List<String> cur_res, List<List<String>> result) {
if(start == s.length()) {
result.add(new ArrayList<String>(cur_res));
return;
}
for(int len = 1; len <= s.length() - start; len++) {
String candidate_str = s.substring(start, start + len);
if(ifPalindrome(candidate_str)) {
cur_res.add(candidate_str);
backtrack(s, start + len, cur_res, result);
cur_res.remove(cur_res.size() - 1);
}
}
}
private boolean ifPalindrome(String str) {
int left = 0, right = str.length() - 1;
while(left < right) {
if(str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}