Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
解法:
DFS,关键在于递归的写法。一开始没想明白,后来套用树的图就想通了。
public class Solution {
public List<String> letterCombinations(String digits) {
// 建立映射表
String[] phone = {" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<String>();
if(digits.length()==0)return res;
dfs(0,digits.length(),"",phone,digits,res);
return res;
}
public void dfs(int x,int length,String str,String[] phone, String digits,List<String> res){
if(x == length){
//找到一个答案,返回
res.add(str);
return;
}
int d = digits.charAt(x)-'0';
for(int i=0;i<phone[d].length();i++){
dfs(x+1,length,str+phone[d].charAt(i),phone,digits,res);
}
}
}