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.
题目是说,就想手机键盘一样,连续按下几个数字按键,会有不同的字母的组合,要求把所有的组合按顺序列出来。(输入为空时,返回为空list)
下面使用深度优先遍历算法解题。
java解题:
public static List<String> letterCombinations(String digits) {
String[] phone = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> res = new ArrayList<String>();
StringBuffer s = new StringBuffer(digits.length());
if(digits.length()<=0)
return res;
search(phone,res,0,digits,s);
return res;
}
public static void search(String[] phone, List<String> res, int index, String digits, StringBuffer s) {
if(index==digits.length()){
res.add(s.toString());
System.out.println(s);
return;
}
int temp = Integer.parseInt(digits.charAt(index)+"")-2;
for(int i=0;i<phone[temp].length();i++){
s.replace(index, index+1, phone[temp].charAt(i)+"");
search(phone, res, index+1, digits, s);
}
}