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"]
]
题目链接:https://leetcode.com/problems/palindrome-partitioning/
题目分析:典型的DFS,搜索的时候维护一个当前区间并判断
题目分析:典型的DFS,搜索的时候维护一个当前区间并判断
public class Solution {
boolean judge(String s) {
int len = s.length();
for(int i = 0; i < len / 2; i ++) {
if(s.charAt(i) != s.charAt(len - i - 1)) {
return false;
}
}
return true;
}
void DFS(String s, int st, int ed, int len, List<String> cur, List<List<String>> ans) {
if(ed == len) {
if(st == len) {
//这里不能写成 ans.add(cur);
ans.add(new ArrayList<String>(cur));
}
return;
}
String str = new String(s.substring(st, ed + 1));
if(judge(str)) {
cur.add(str);
DFS(s, ed + 1, ed + 1, len, cur, ans);
cur.remove(cur.size() - 1);
}
DFS(s, st, ed + 1, len, cur, ans);
}
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<>();
int len = s.length();
List<String> cur = new ArrayList<>();
DFS(s, 0, 0, len, cur, ans);
return ans;
}
}