九章算法 | Facebook面试题:电话号码的字母组合

给一个不包含​0​和​1​的数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。

下图的手机按键图,就表示了每个数字可以代表的字母。

12
ABC
3
DEF
4
GHI
5
JKL
6
MNO
7
PQRS
8
TUV
9
WXYZ
  • 以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

在线评测地址:LintCode 领扣

样例 1:

输入: "23"
输出: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
解释: 
'2' 可以是 'a', 'b' 或 'c'
'3' 可以是 'd', 'e' 或 'f'

样例 2:

输入: "5" 
输出: ["j", "k", "l"]

算法:DFS

  1. 如果输入的数字串为空,返回空列表;
  2. 预处理存储1-9各个数字可以对应的字母;
  3. 对数字串进行深度优先搜索,传入的参数包括:数字串digits、当前的位置index、当前存入的字符串current、保存答案的字符串列表result、数字字母映射的字符串数组phone。
  • 当前位置达到数字串末尾即达到边界,将current添加到result,回溯;
  • 对index位置的数字通过phone找出可以选用的每个字母,分别递归调用dfs;
  • 递归步进为:index+1, current+选用的字母;

复杂度分析

  • 时间复杂度:O(4^n), n为数字串长度
    • 每个数字都有3-4个可对应的字母
  • 空间复杂度:O(4^n),n为数字串长度
    • 对于用来保存答案的列表,最多有4^n种组合
public class Solution {
        /**
         * @param digits: A digital string
         * @return: all posible letter combinations
         */
    
        public static final HashMap<Integer, String> PHONE = new HashMap<Integer, String>() {
            {
                put(0, ""); put(1, ""); 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) {
            List<String> result = new ArrayList<>();
            if (digits.length() == 0) {
                return result;
            }
            dfs(0, "", digits, PHONE, result);
            return result;
        }
    
        private void dfs(int index, String current, String digits, HashMap<Integer, String> PHONE, List<String> result) {
            if (index == digits.length()) {
                result.add(current);
                return;
            }
    
            int d = digits.charAt(index) - '0';
            for (char c : PHONE.get(d).toCharArray()) {
                dfs(index + 1, current + c, digits, PHONE, result);
            }
        }
    }

更多题解参考:九章算法

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值