It said recursive encoding is an easy to understand, but the feeling is not so easy.
Today brush leetCode encountered a problem division palindrome string, as follows:
Given a string s, s is divided into a number of sub-strings, each sub-string is a string palindrome.
S return all the possible partitioning scheme.
Example:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/palindrome-partitioning
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Among them the use of DFS and backtracking solution
The complete code is as follows
package com.LeeCode;
import java.util.ArrayList;
import java.util.List;
public class VariesPalindrome {
List<List<String>>list=new ArrayList<List<String>>();
String s;
public List<List<String>> partition(String s) {
//从头到尾递归+回溯。
this.s=s;
//这个是满足的每一个集合
List<String>ll=new ArrayList<String>();
dfs(ll,0);
return list;
}
public void dfs(List<String>ll,int index){
if(index==s.length())
{
list.add(new ArrayList<String>(ll));
return;
}
// i is because a single character is palindromic substring from index
for (int I = index; I <s.length (); I ++)
{
// If palindromic
IF (isPalindrome (index, I)) {
// the current palindromic substring s (index, i) added to the list
ll.add (s.substring (index, I +. 1));
DFS (LL, I +. 1);
// add the palindromic substring into place. The above and added into the same palindrome is a palindrome substring substring.
ll.remove (ll.size () -. 1);
}
}
}
public Boolean isPalindrome (int Start, End int) {
the while (Start <End) {
! IF (s.charAt (Start) = s.charAt (End) )
return false;
Start ++;
end--;
}
return true;
}
public static void main(String[] args) {
VariesPalindrome variesPalindrome=new VariesPalindrome();
String jj="abnnss";
System.out.println(variesPalindrome.partition(jj));
}
}