思路 参数里调用上一个list 读取出来 再加上新的letter组成新的string加入到新的list中,最后返回新的list
代码:
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
for(int i = 0; i < digits.length(); i++){
char c = digits.charAt(i);
list = addLetter(list, c);
}
return list;
}
public List<String> addLetter(List<String> list, char c){
if(c == ‘1‘ || c == ‘0‘) return list;
int len = list.size();
List<String> newList = new ArrayList<>();
int i = (int) (c - ‘2‘);
if(len == 0){
if(i>=0 && i<=4){
for(int j = 0; j < 3; j++){
char ch = (char) (‘a‘+3*i+j);
newList.add(""+ch);
}
}
else if(i == 5){
newList.add(""+ ‘p‘);
newList.add(""+ ‘q‘);
newList.add(""+ ‘r‘);
newList.add(""+ ‘s‘);
}
else if(i == 6){
newList.add(""+ ‘t‘);
newList.add(""+ ‘u‘);
newList.add(""+ ‘v‘);
}
else{
newList.add(""+ ‘w‘);
newList.add(""+ ‘x‘);
newList.add(""+ ‘y‘);
newList.add(""+ ‘z‘);
}
return newList;
}
for(int k = 0; k < len; k++){
String s = list.get(k);
if(i>=0 && i<=4){
for(int j = 0; j < 3; j++){
char ch = (char) (‘a‘+3*i+j);
newList.add(s+ch);
}
}
else if(i == 5){
newList.add(s+ ‘p‘);
newList.add(s+ ‘q‘);
newList.add(s+ ‘r‘);
newList.add(s+ ‘s‘);
}
else if(i == 6){
newList.add(s+ ‘t‘);
newList.add(s+ ‘u‘);
newList.add(s+ ‘v‘);
}
else{
newList.add(s+ ‘w‘);
newList.add(s+ ‘x‘);
newList.add(s+ ‘y‘);
newList.add(s+ ‘z‘);
}
}
return newList;
}
}
Jan 15 - Letter Combination of Phone Number; BackTracing; Recursion; String
原文:http://www.cnblogs.com/5683yue/p/5134871.html