classSolution{ public String nums = "23456789"; public List<String> res = new ArrayList<>(); public Map<Character, String> dict = new HashMap<>(); public String[] words = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits){ if (digits == null || digits.isEmpty()) return res; for (int i = 0; i < nums.length(); i++) { dict.put(nums.charAt(i), words[i]); } dfs(digits, 0, new StringBuilder()); return res; }
publicvoiddfs(String digits, int index, StringBuilder builder){ if (index == digits.length()) { res.add(builder.toString()); return; } String word = dict.get(digits.charAt(index)); for (int i = 0; i < word.length(); i++) { builder.append(word.charAt(i)); dfs(digits, index + 1, builder); builder.deleteCharAt(index); } } }