题目:
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
数据结构看起来这就是个3-4叉树,需要遍历出所有到根节点的路径,并打印出路径上的节点
基本思想采用递归算法,假设substring(1)已经返回了一个List<String>,那么我们只需要对List中的元素前缀分别加上charAt(0)所对应的字母即可。
import java.util.ArrayList;
import java.util.List;
public class No18_LetterCombinationsOfAPhoneNumber {
public static void main(String[] args){
System.out.println(letterCombinations("234567"));
}
public static List<String> letterCombinations(String digits) {
List<String> ret = (List)new ArrayList<String>();
if(digits.length() == 0){
ret.add("");
return ret;
}
List<String> last = letterCombinations(digits.substring(1));
int index = digits.charAt(0)-'0';
for(int i=0;i<last.size();i++){
String s = last.get(i);
switch(index){
case 2:
ret.add("a"+s);
ret.add("b"+s);
ret.add("c"+s);
break;
case 3:
ret.add("d"+s);
ret.add("e"+s);
ret.add("f"+s);
break;
case 4:
ret.add("g"+s);
ret.add("h"+s);
ret.add("i"+s);
break;
case 5:
ret.add("j"+s);
ret.add("k"+s);
ret.add("l"+s);
break;
case 6:
ret.add("m"+s);
ret.add("n"+s);
ret.add("o"+s);
break;
case 7:
ret.add("p"+s);
ret.add("q"+s);
ret.add("r"+s);
ret.add("s"+s);
break;
case 8:
ret.add("t"+s);
ret.add("u"+s);
ret.add("v"+s);
break;
case 9:
ret.add("w"+s);
ret.add("x"+s);
ret.add("y"+s);
ret.add("z"+s);
break;
case 0:
ret.add(" "+s);
}
}
return ret;
}
}