Give a string, you can choose to split the string after one character or two adjacent characters, and make the string to be composed of only one character or two characters. Output all possible results.
Example
Example1
Input: "123"
Output: [["1","2","3"],["12","3"],["1","23"]]
Example2
Input: "12345"
Output: [["1","23","45"],["12","3","45"],["12","34","5"],["1","2","3","45"],["1","2","34","5"],["1","23","4","5"],["12","3","4","5"],["1","2","3","4","5"]]
思路:选1或者选2
public class Solution {
/*
* @param : a string to be split
* @return: all possible split string array
*/
public List<List<String>> splitString(String s) {
List<List<String>> lists = new ArrayList<List<String>>();
if(s == null) return lists;
List<String> list = new ArrayList<String>();
dfs(s, 0, list, lists);
return lists;
}
private void dfs(String s, int index, List<String> list, List<List<String>> lists) {
if(index == s.length()){
lists.add(new ArrayList<String>(list));
return;
}
// choose 1;
list.add(s.substring(index, index+1));
// explore
dfs(s, index+1, list, lists);
// unchoose 1;
list.remove(list.size() -1);
if(index+2 <= s.length()) {
// choose 2;
list.add(s.substring(index, index+2));
// explore
dfs(s, index+2, list, lists);
// unchoose 2;
list.remove(list.size() -1);
}
}
}
思路2:写成模板形式,技巧在于i可以走一步,两步,走到第三步,也就是i - index >1 的时候,就要continue;substring 起点是index即可,那么substring就可以取1或者取2;
public class Solution {
/*
* @param : a string to be split
* @return: all possible split string array
*/
public List<List<String>> splitString(String s) {
List<List<String>> lists = new ArrayList<List<String>>();
if(s == null){
return lists;
}
List<String> list = new ArrayList<String>();
dfs(s, list, lists, 0);
return lists;
}
private void dfs(String s, List<String> list, List<List<String>> lists, int index) {
if(index == s.length()) {
lists.add(new ArrayList<String>(list));
return;
}
for(int i = index; i < s.length(); i++) {
if(i - index > 1) {
continue;
}
list.add(s.substring(index, i+1));//注意这里一定是i+1,否则substring(i,i)死循环;
dfs(s, list, lists, i+1);
list.remove(list.size() -1);
}
}
}