这是我参与 8 月更文挑战的第 12 天,活动详情查看: 8月更文挑战
⚽题目
给定一个仅包含数字 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'] 的一个数字。
通过次数313,172提交次数548,644
⚽一点点思路
哈哈哈是不是绝的这题特简单直接循环呗,而且你看它的提示输入字符串的长度小于等于4。我觉的直接循环没什么问题吧。但是我们既然讲了这道题肯定不能这么简单粗暴了。我们就用一个听起来很厉害的方法“回溯(su)法”什么叫回溯呢说白了递归。
⚽开干
⚽介绍一种函数
之前我们说过HashMap和StringBuilder今天我们用了StringBuffer()具体的用法就不说了它和StringBuider用法还是挺相同的。这里重点说一下不同和区分
- 不同:他们的原理和操作基本相同,区别在于StringBufferd支持并发操作,线性安全的,适 合多线程中使用。StringBuilder不支持并发操作,线性不安全的,不适合多线程中使用。新引入的StringBuilder类不是线程安全的,但其在单线程中的性能比StringBuffer高。
- 适用情况:不必考虑到线程同步问题,我们应该优先使用StringBuilder类;如果要保证线程安全,自然是StringBuffer。
⚽源码和详解
public class Solution {
public static void backtrack(List<String> combinations,Map<Character,String[]> map,String digits,StringBuffer combination,int index) {
if(digits.length()==index) {
combinations.add(combination.toString());
}else {
char d=digits.charAt(index);
String[] j=map.get(d);
//int jCount=j.length;
for(int i=0;i<j.length;i++) {
combination.append(j[i]);
backtrack(combinations, map, digits, combination, index+1);
combination.deleteCharAt(index);
}
}
}
public static List<String> letterCombinations(String digits) {
List<String> combinations=new ArrayList<String>();
HashMap<Character,String[]> map=new HashMap<Character,String[]>() {{
put('2', new String[]{"a", "b", "c"});
put('3', new String[]{"d", "e", "f"});
put('4', new String[]{"g", "h", "i"});
put('5', new String[]{"j", "k", "l"});
put('6', new String[]{"m", "n", "o"});
put('7', new String[]{"p", "q", "r", "s"});
put('8', new String[]{"t", "u", "v"});
put('9', new String[]{"w", "x", "y", "z"});
}};
backtrack(combinations, map, digits, new StringBuffer(), 0);
return combinations;
}
public static void main(String[] args) {
System.out.println(letterCombinations("23"));
}
}
其他的我就不说了,因为挺简单的我就说说这个回溯这部分吧
//首先要明白这个带入的变量都是干嘛的combinations自然是存放最终结果的map是之前用来存放每个数字对应的字母
//digits是输入的字符串combination是用来一会拼接字符的,index是用来移动输入字符的指针如“234”是来移动指向
//2还是3还是4用的
public static void backtrack(List<String> combinations,Map<Character,String[]> map,String digits,StringBuffer combination,int index) {
//用来将满足条件的字符串存入到最终List里
if(digits.length()==index) {
combinations.add(combination.toString());
}else {
char d=digits.charAt(index);//得到例如“234”是2或3或4
String[] j=map.get(d);//得到每个数字对应的字母数组
for(int i=0;i<j.length;i++) {
combination.append(j[i]);//用来拼接字符
backtrack(combinations, map, digits, combination, index+1);//回溯
combination.deleteCharAt(index);//删除
}
}
}
好了今天的算法就介绍到这里了,我们明天再见吧。