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"] ]
回溯法
说明
用对于每个子集检测是否是回文串, 如果是就从下一个指针来继续搜索.
复杂度
时间O(2^n)
代码
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if (s == null || s.length() == 0) {
return res;
}
List<String> tem = new ArrayList<String>();
helper(s, res, tem, 0);
return res;
}
public void helper(String s, List<List<String>> res, List<String> tem, int pos) {
if (pos == s.length()) {
res.add(new ArrayList<String>(tem));
return;
}
for (int i = pos; i < s.length(); i++) {
if (isValid(s.substring(pos, i + 1))) {
tem.add(s.substring(pos, i + 1));
helper(s, res, tem, i + 1);
tem.remove(tem.size() - 1);
}
}
}
public boolean isValid(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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。