Letter Combinations of a Phone Number
Source
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)
given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Java
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits.length()==0) return result;
HashMap<Character, String> map = new HashMap<Character, String>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
dfs(digits, "", 0, map, result);
return result;
}
public void dfs(String digits, String path, int index, HashMap<Character, String> map, List<String> result){
if(index == digits.length()){
result.add(path);
return;
}
char num = digits.charAt(index);
String letters = map.get(num);
for(int i=0; i<letters.length(); i++){
char c = letters.charAt(i);
dfs(digits, path+c, index+1, map, result);
}
}
}