问题描述
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 ArrayList<String> letterCombinations(String digits) {
ArrayList<String> result = new ArrayList<>();
HashMap<Character, char[]> hashMap = new HashMap<>();
hashMap.put('0', new char[]{' '});
hashMap.put('2', new char[]{'a', 'b', 'c'});
hashMap.put('3', new char[]{'d', 'e', 'f'});
hashMap.put('4', new char[]{'g', 'h', 'i'});
hashMap.put('5', new char[]{'j', 'k', 'l'});
hashMap.put('6', new char[]{'m', 'n', 'o'});
hashMap.put('7', new char[]{'p', 'q', 'r', 's'});
hashMap.put('8', new char[]{'t', 'u', 'v'});
hashMap.put('9', new char[]{'w', 'x', 'y', 'z'});
getString(digits, 0, result, "", hashMap);
return result;
}
private void getString(String digits, int position, ArrayList<String> result,
String str, HashMap<Character, char[]> hashMap) {
if (position < digits.length()) {
if (hashMap.containsKey(digits.charAt(position))) {
for (char c : hashMap.get(digits.charAt(position))) {
String newStr = str + c;
getString(digits, position + 1, result, newStr, hashMap);
}
}
} else result.add(str);
}
网友评论