131. Palindrome Partitioning
刷
July-14-2019
没秒了,不应该啊。。想复杂了,没必要带着当前string进入下一层,直接加到TEMPLIST里
abc =>
dfs([a], bc) -> dfs([ab], c) -> dfs([abc], c)
dfs([a,b], c) -> dfs([a, bc], "")
Time: O(2^n)
// T(n) = T(n-1) + T(n-2) + T(n-3) ... + T(1)
// T(n-1) = T(n-2) + T(n-3) ... + T(1)
// T(n) = 2T(n-1)
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.length() == 0) return res;
dfs(res, s, new ArrayList<>());
return res;
}
// T(n) = T(n-1) + T(n-2) + T(n-3) ... + T(1)
// T(n-1) = T(n-2) + T(n-3) ... + T(1)
// T(n) = 2T(n-1)
public void dfs(List<List<String>> res, String s, List<String> tempList) {
if (s.length() == 0) {
res.add(new ArrayList<>(tempList));
} else {
for (int i = 1; i <= s.length(); i ++) {
String leftStr = s.substring(0, i);
if (!isPalindrome(leftStr)) continue;
tempList.add(leftStr);
dfs(res, s.substring(i), tempList);
tempList.remove(tempList.size() - 1);
}
}
}
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
if (s.charAt(l ++) != s.charAt(r --)) {
return false;
}
}
return true;
}
}
三刷。
DFS + BACKTRACK
T(n) = T(n - 1) + T(n-2) + ..+ T(n-1)
T(n) = 2T(n-1) = 4T(n-2) = 2^n T(1)
isValid: O(n)
Time: O(n*2^n)
space: O(2^n) 跟一个STRING能有多少种分法一样。。
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if (s.length() == 0) return res;
dfs(res, s, new ArrayList<>());
return res;
}
public void dfs(List<List<String>> res, String s, List<String> tempList) {
if (s.length() == 0) {
res.add(tempList);
return;
} else {
for (int i = 1; i <= s.length(); i++) {
String str1 = new String(s.substring(0,i));
if (!isValid(str1)) continue;
String str2 = new String(s.substring(i));
tempList.add(str1);
dfs(res, str2, new ArrayList<>(tempList));
tempList.remove(tempList.size() - 1);
}
return;
}
}
public boolean isValid(String s) {
if (s.length() <= 1) return true;
int l = 0;
int r = s.length() - 1;
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
}
以前做出来自鸣得意,现在回头看,难点从来都不是题本身,而是时间和空间的复杂度…

浙公网安备 33010602011771号