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

17. 电话号码的字母组合

作者头像
用户7447819
发布2021-07-23 14:35:41
3310
发布2021-07-23 14:35:41
举报
文章被收录于专栏:面试指北面试指北

LeetCode17. 电话号码的字母组合

1. 题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

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

2. 题解 - 回溯算法

代码语言:javascript
复制
class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if(digits.length() == 0) {
            return result;
        }
        Map<Character, String> map = new HashMap<>();
        map.put('2', "abc");
        map.put('3', "def");
        map.put('4', "ghi");
        map.put('5', "jkl");
        map.put('6', "mno");
        map.put('7', "pqrs");
        map.put('8', "tuv");
        map.put('9', "wxyz");

        backTrack(digits, map, result, new StringBuffer(), 0);
        return result;
    }

    private void backTrack(String digits, Map<Character, String> map,List<String> combinations, StringBuffer combination, int index){
        if(digits.length() == index){
            combinations.add(combination.toString());
        } else {
            String letter = map.get(digits.charAt(index));
            for(int i = 0; i < letter.length(); i++) {
                combination.append(letter.charAt(i));
                backTrack(digits, map, combinations, combination, index + 1);
                combination.deleteCharAt(index);
            }
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-12-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面试指北 微信公众号,前往查看

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

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

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