# LeetCode 100题题解(JAVA) 17 电话号码的字母组合
前言
提示:简单记录一下答案和思路,参考或者复制网上的思路。
提示:以下是本篇文章正文内容,下面案例可供参考
简单记录一下答案和思路。
一、题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例 2:
输入:digits = “”
输出:[]
示例 3:
输入:digits = “2”
输出:[“a”,“b”,“c”]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
二、解题思路
1.递归思路,拼接用子问题的解
以输入digits = "23"为例, '2'对应"abc", '3'对应"def" .主问题2的解释 a b c,子问题3的解就是 d e f, 在a后面分别拼接d e f, b c 同理
做法是遍历2的解,在搜索到第一个解a的下一步,就立即调用递归方法,在a的基础上,拼接3的第一个解d. 递归方法的第一行写好出口,方便每次判断是否满足退出当前小递归的条件.
2.注意递归要有一个临时存储结果的容器
用一个StringBuffer 临时存储问题的解.该容器要传入每次的递归调用中.
为了拼接子问题的多个答案,要在下一次循环中,删除当前子问题的解,同时子问题循环完之后,也可以删除当前主问题a的解,可以缓存下一个解b.
3.代码如下
class Solution {
public List<String> letterCombinations(String digits) {
//用ArrayList存储结果,元素是Obeject,指定String
List<String> combinations = new ArrayList<String>();
if (digits.length() == 0) {
return combinations;
}
//HashMap哈希表存储按键对应的字母
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");
}};
//调用回溯方法,传入存储最终结果的容器combinations,电话号码表phoneMap,字符串digits,初始下标为0,new一个StringBuffer暂存得要的结果
backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
return combinations;
}
//编写回溯方法
public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
//定义递归的出口,走完字符串就存储一次结果
if (index == digits.length()) {
combinations.add(combination.toString());
} else {
//拿到index对应的字符复制给digit
char digit = digits.charAt(index);
//在HashMap哈希表中查到对应的字母组合
String letters = phoneMap.get(digit);
//找到该组合的长度,方便作为循环终止条件
int lettersCount = letters.length();
//开始循环取数
for (int i = 0; i < lettersCount; i++) {
//取到index的第i个字母,加入到临时容器combination中,第一次取到index=0对应的i=0字母
combination.append(letters.charAt(i));
//调用递归方法,跳到index+1去,又会执行到上一行代码处,直到满足递归出口才跳出递归
backtrack(combinations, phoneMap, digits, index + 1, combination);
//删除子问题的解,方便拼接子问题的下一个解
combination.deleteCharAt(index);
}
}
}
}
总结
1.掌握代码中的递归写法
2.熟练使用StringBuffer类的append方法拼接字符
3.