2017.9.29
如果单纯的使用递归的方式的话,会超出内存的限制。 F(S ) = F(s-1) + F(s-2)
采用显式的递归就过了
public class Solution {
/*
* @param : a string to be split
* @return: all possible split string array
*/
public static List<List<String>> initTmp1(String s) {
List<List<String>> res1 = new LinkedList<>();
List<String> tmp1 = new LinkedList<String>();
tmp1.add(s.substring(0,1));
res1.add(tmp1);
return res1;
}
public static List<List<String>> initTmp2(String s) {
List<List<String>> res2 = new LinkedList<>();
List<String> tmp1 = new LinkedList<String>();
List<String> tmp2 = new LinkedList<String>();
tmp1.add(s.substring(0,1));
tmp1.add(s.substring(1,2));
res2.add(tmp1);
tmp2.add(s.substring(0,2));
res2.add(tmp2);
return res2;
}
public static List<List<String>> splitString(String s) {
// write your code here
int size = s.length();
List<List<String>> res1 = new LinkedList<>();
List<List<String>> res2 = new LinkedList<>();
if(size == 0){
List<String> tmp = new LinkedList<String>();
res1.add(tmp);
return res1;
}
res1 = initTmp1(s);
if(size == 1){
return res1;
}
// 先初始化 res1中存放 f(n-2)
// res2中存放 f(n-1);L
res2 = initTmp2(s);
if(size == 2){
return res2;
}
int i = 3;
while(s.length() >= i){
for(List list1 : res1){
list1.add(s.substring(i-2, i));
}
for(List list2 : res2){
LinkedList<String> tmp = new LinkedList<String>();
tmp.addAll(list2);
tmp.add(s.substring(i-1, i));
res1.add(tmp);
}
List<List<String>> resTmp = new LinkedList<>();
resTmp = res1;
res1 = res2;
res2 = resTmp;
i++;
}
return res2;
}
}