Total Accepted: 8862 Total Submissions: 34390
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.
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> list = new ArrayList<String>();
char[][] keyMap = {{}, {'a','b','c'}, {'d','e','f'}, {'g','h','i'}, {'j','k','l'},
{'m','n','o'}, {'p','q','r','s'}, {'t','u','v'}, {'w','x','y','z'}};
dfs(list, "", digits, keyMap);
return list;
}
public void dfs(ArrayList<String> list, String path, String digits, char[][] keyMap) {
if (path.length() == digits.length()) {
list.add(path);
return;
} else {
int num = digits.charAt(path.length()) - '1';
for (int i = 0; i < keyMap[num].length; i++) {
dfs(list, path + keyMap[num][i], digits, keyMap);
}
}
}
}