1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { List<String> res = new ArrayList<>(); StringBuffer sb = new StringBuffer(); public List<String> letterCombinations(String digits) { if (digits == null || digits.length() == 0) { return res; } String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; backtracking(0, digits, numString); return res; }
public void backtracking(int index, String digits, String[] numString) { if (index == digits.length()) { res.add(sb.toString()); return; }
String str = numString[digits.charAt(index) - '0']; for (int i = 0; i < str.length(); i++) { sb.append(str.charAt(i)); backtracking(index + 1, digits, numString); sb.deleteCharAt(sb.length() - 1); } } }
|