电话号码的字母组合
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
0 <= digits.length <= 4
digits[i]
是范围['2', '9']
的一个数字。
题解
经典的回溯的思想,没什么特别的地方
class Solution {List<String> ans = new ArrayList<String>();Map<Character, String> phoneMap = new HashMap<Character, String>() {{put('2', "abc");put('3', "def");put('4', "ghi");put('5', "jkl");put('6', "mno");put('7', "pqrs");put('8', "tuv");put('9', "wxyz");}};public List<String> letterCombinations(String digits) {if(digits.length() == 0){return ans;}StringBuffer str = new StringBuffer();letterCombinations(digits, 0, str);return ans;}private void letterCombinations(String digits, int index, StringBuffer str) {if (index == digits.length()) {ans.add(str.toString());return;}String phone = phoneMap.get(digits.charAt(index));for (int i = 0; i < phone.length(); i++) {str.append(phone.charAt(i));letterCombinations(digits, index + 1, str);str.deleteCharAt(str.length() - 1);}}
}
var phoneMap = map[byte]string{'2': "abc",'3': "def",'4': "ghi",'5': "jkl",'6': "mno",'7': "pqrs",'8': "tuv",'9': "wxyz",
}func letterCombinations(digits string) []string {var ans []string = []string{}if len(digits) == 0 {return ans}letterCombinationsHelper(digits, 0, "", &ans)return ans
}func letterCombinationsHelper(digits string, index int, str string, ans *[]string) {if index == len(digits) {*ans = append(*ans, str)return}phone := phoneMap[digits[index]]for i := 0; i < len(phone); i++ {str += string(phone[i])letterCombinationsHelper(digits, index+1, str, ans)str = str[:len(str)-1]}
}