电话号码的字母组合
电话号码的字母组合 给定一个仅包罗数字 2-9 的字符串,返回全部它能体现的字母组合。答案可以按 恣意次序 返回。
给出数字到字母的映射如下(与电话按键相同)。留意 1 不对应任何字母。
https://img-blog.csdnimg.cn/img_convert/1965447780dc06f0d86b0f8debe919a3.png
示例 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 是范围 ['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 = mapstring{
'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]
for i := 0; i < len(phone); i++ {
str += string(phone)
letterCombinationsHelper(digits, index+1, str, ans)
str = str[:len(str)-1]
}
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]