算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。
今天和大家聊的问题叫做电话号码的字母组合 ,我们先来看题面:
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
题意
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。样例
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
题解
这是个排列组合问题对吧?这个排列组合可以用树的形式表示出来;当给定了输入字符串,比如:"23",那么整棵树就构建完成了,如下: 问题转化成了从根节点到空节点一共有多少条路径;
class Solution {
public List<String> letterCombinations(String digits) {
// 数字与字母的对应关系
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<>();
if(digits.isEmpty())
return res;
// 图中树的根节点
res.add("");
// 遍历输入的数字
for(char c : digits.toCharArray()){
res = combine(map[c-'0'], res);
}
return res;
}
// 根据数字组合字母
private List<String> combine(String digits, List<String> list){
List<String> res = new ArrayList<>();
for(char c : digits.toCharArray()){
for(String s : list){
res.add(s+c);
}
}
return res;
}
}