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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { public List<String> letterCombinations(String digits) { Map<Character, String> map = new HashMap<>(); 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");
List<String> ans = new LinkedList<>(); List<Character> path = new LinkedList<>();
if (digits.length() > 0) { backtracking(map, ans, path, digits); }
return ans;
}
private void backtracking (Map<Character, String> map, List<String> ans, List<Character> path, String digits) {
if (path.size() == digits.length()) {
StringBuffer sb = new StringBuffer();
for (Character character : path) { sb.append(character); }
ans.add(new String(sb)); return; }
char digit = digits.charAt(path.size()); String str = map.get(digit);
for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); path.add(c);
backtracking(map, ans, path, digits);
path.remove(path.size() - 1); }
} }
|