给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0) {
return result;
}
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");
backTrack(digits, map, result, new StringBuffer(), 0);
return result;
}
private void backTrack(String digits, Map<Character, String> map,List<String> combinations, StringBuffer combination, int index){
if(digits.length() == index){
combinations.add(combination.toString());
} else {
String letter = map.get(digits.charAt(index));
for(int i = 0; i < letter.length(); i++) {
combination.append(letter.charAt(i));
backTrack(digits, map, combinations, combination, index + 1);
combination.deleteCharAt(index);
}
}
}
}