一、Problem
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
二、Solution
方法一:回溯
class Solution {
List<String> it;
List<List<String>> all;
boolean is(String s, int l, int r) {
while (l < r) {
if (s.charAt(l) == s.charAt(r)) {
l++; r--;
} else
return false;
}
return true;
}
void dfs(int idx, String s) {
if (idx == s.length()) {
all.add(new LinkedList<>(it));
return;
}
for (int i = idx; i < s.length(); i++) {
if (is(s, idx, i)) {
it.add(s.substring(idx, i+1));
dfs(i+1, s);
it.remove(it.size()-1);
}
}
}
public List<List<String>> partition(String s) {
it = new LinkedList<>();
all = new LinkedList<>();
dfs(0, s);
return all;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,