前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >回溯算法 17. 电话号码的字母组合

回溯算法 17. 电话号码的字母组合

作者头像
MashiroT
发布2023-01-30 14:57:58
2360
发布2023-01-30 14:57:58
举报
文章被收录于专栏:MashiroのBlog

回溯算法 17. 电话号码的字母组合

回溯算法用于寻找所有的可行解,如果发现一个解不可行,则会舍弃不可行的解。

在这道题中,由于每个数字对应的每个字母都可能进入字母组合,因此不存在不可行的解,直接穷举所有的解即可。

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:

代码语言:javascript
复制
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

代码语言:javascript
复制
输入:digits = ""
输出:[]

示例 3:

代码语言:javascript
复制
输入:digits = "2"
输出:["a","b","c"]

提示:

代码语言:javascript
复制
0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。

代码

代码语言:javascript
复制
public static List<String> letterCombinations(String digits) {
    if ("".equals(digits)) {
        return new ArrayList<>(0);
    }
    List<String> rsList = new ArrayList<>((int) Math.pow(3, digits.length()));
    Map<Character, List<Character>> map = Map.of(
            '2', List.of('a', 'b', 'c'), '3', List.of('d', 'e', 'f'),
            '4', List.of('g', 'h', 'i'), '5', List.of('j', 'k', 'l'),
            '6', List.of('m', 'n', 'o'), '7', List.of('p', 'q', 'r', 's'),
            '8', List.of('t', 'u', 'v'), '9', List.of('w', 'x', 'y', 'z')
    );
//        例:digits = "2"
    generateString(digits, 0, rsList, map, new StringBuilder());
    return rsList;
}

private static void generateString(String str, int p, List<String> list, Map<Character, List<Character>> map, StringBuilder sb) {
    if (p == str.length()) {
        list.add(sb.toString());
        return;
    }
//        'a', 'b', 'c'
    for (Character ch : map.get(str.charAt(p))) {
//            1. a
//            2. b
//            3. c
        sb.append(ch);
//            递归进入 p == 1   str.len == 1
//            toString加入集合后返回
        generateString(str, p + 1, list, map, sb);
//            1. 删除a
//            2. 删除b
//            3. 删除c
        sb.deleteCharAt(p);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-12-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 回溯算法 17. 电话号码的字母组合
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档