# 131. Palindrome Partitioning

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"]
]

#### Solution1：Backtracking(DFS)，

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()) {
}

for(int i = start; i < s.length(); i++) {
if(!isPalindrome(s, start, i)) {
continue;
}
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()) {
return;
}

for(int len = 1; len <= s.length() - start; len++) {
String candidate_str = s.substring(start, start + len);
if(ifPalindrome(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;
}
}
``````