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 1:
- Input: digits = "23"
- Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
- Input: digits = ""
- Output: []
Example 3:
- Input: digits = "2"
- Output: ["a","b","c"]
Constraints:
- public class Solution {
- public List
letterCombinations(String digits) { - List
result = new ArrayList(); - if(digits == null || digits.length() == 0){
- return result;
- }
- Map
char[]> map = new HashMapchar[]>(); - map.put('2', new char[]{'a', 'b', 'c'});
- map.put('3', new char[]{'d', 'e', 'f'});
- map.put('4', new char[]{'g', 'h', 'i'});
- map.put('5', new char[]{'j', 'k', 'l'});
- map.put('6', new char[]{'m', 'n', 'o'});
- map.put('7', new char[]{'p', 'q', 'r', 's'});
- map.put('8', new char[]{'t', 'u', 'v'});
- map.put('9', new char[]{'w', 'x', 'y', 'z'});
- StringBuilder sb = new StringBuilder();
- dfs(digits, sb, map, result);
- return result;
- }
-
- public void dfs(String digits, StringBuilder sb, Map
char []> map, List result){ - if(sb.length() == digits.length()){
- result.add(sb.toString());
- return;
- }
- for(char c : map.get(digits.charAt(sb.length()))){
- sb.append(c);
- dfs(digits, sb, map, result);
- sb.deleteCharAt(sb.length() - 1);
- }
- }
- }