参考资料:左程云算法课
- 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.
Example 1:
Input: s = “aab”
Output: [[“a”,“a”,“b”],[“aa”,“b”]]
思路:
枚举第一个划分位置,如”abc“。其第一个划分位置end所有可能的结果是 “a”, “ab”, “abd”;然后判断是否回文,如果是,那么调用子递归,解决end+1到len-1上的划分问题。
其中,判断str[l…r]是否是回文,可以用动态规划的方法提前计算好放进dp表,作为递归函数的参数,让递归函数带着跑,需要查的时候就查一下。
public List<List<String>> partition(String s) {
List<List<String>> ans=new ArrayList<>();
LinkedList<String> path = new LinkedList<>();
boolean[][] dp = getdp(s.toCharArray());
// dp[i][j] means whether or not s[i..j] is parlindrome
process(s,0,dp,path,ans);
return ans;
}
public void process(String s, int index, boolean[][] dp, LinkedList<String> path, List<List<String>> ans)
{
if(index==s.length())
{
ans.add(copy(path));
return;
}
// index...end
for(int end=index;end<s.length();end++)
{
if(dp[index][end]) // [index..end] is parlindrome
{
path.addLast(s.substring(index,end+1));
process(s,end+1,dp,path,ans);
path.pollLast();// 深度优先遍历,清理现场
}
}
}
public boolean[][] getdp(char[] str)
{
int n = str.length;
boolean[][] dp = new boolean[n][n];
for(int i=0;i<n-1;i++)
{
dp[i][i] = true;
dp[i][i+1]=str[i]==str[i+1];
}
dp[n-1][n-1]=true;
// i=n-3 , n-4, ...0
// dp[i][j] = [i][j]&&dp[i+1][j-1]
for(int i=n-3;i>=0;i--)
{
for(int j=i+2;j<n;j++)
{
dp[i][j] = str[i]==str[j] && dp[i+1][j-1];
}
}
return dp;
}
public List<String> copy(LinkedList<String> path)
{
List<String> ans = new ArrayList<>();
for(String s:path)
{
ans.add(s);
}
return ans;
}