描述:
给定一个仅包含数字 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'] 的一个数字。
Soulution:
public static void main(String[] args) {
// [ad, ae, af, bd, be, bf, cd, ce, cf]
System.out.println(letterCombinations("23"));
// []
System.out.println(letterCombinations(""));
// [a, b, c]
System.out.println(letterCombinations("2"));
}
static HashMap<Character, String[]> numToLetterMap = new HashMap<Character, String[]>(8) {
{
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"});
}
};
public static List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits.length() <= 0) {
return result;
}
// 递归
findNextLetter(result, digits.toCharArray(), 0, "");
return result;
}
private static void findNextLetter(List<String> result, char[] digits, int index, String tempStrBd) {
if (digits.length == index) {
result.add(tempStrBd);
return;
}
// 取出对应字符
String[] strings = numToLetterMap.get(digits[index]);
for (String string : strings) {
String temp = tempStrBd + string;
findNextLetter(result, digits, index + 1, temp);
}
}
Idea:
递归,虽然时间复杂度没有很低,但代码优雅
Reslut: