前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 17. Letter Combinations of a Phone Number题目分析代码

LeetCode 17. Letter Combinations of a Phone Number题目分析代码

作者头像
desperate633
发布2018-08-22 14:22:56
2380
发布2018-08-22 14:22:56
举报
文章被收录于专栏:desperate633desperate633

题目

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

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

Paste_Image.png

注意事项

以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

样例 给定 "23"

返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

分析

深度搜索方法和回溯法

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> res = new ArrayList<>();
        
        
        HashMap<Character, char[]> map = new HashMap<>();
        
        map.put('0', new char[] {});
        map.put('1', new char[] {});
        map.put('2', new char[] { 'a', 'b', 'c' });
        map.put('3', new char[] { 'd', 'e', 'f' });
        map.put('4', new char[] { 'g', 'h', 'i' });
        map.put('5', new char[] { 'j', 'k', 'l' });
        map.put('6', new char[] { 'm', 'n', 'o' });
        map.put('7', new char[] { 'p', 'q', 'r', 's' });
        map.put('8', new char[] { 't', 'u', 'v'});
        map.put('9', new char[] { 'w', 'x', 'y', 'z' });
        
        StringBuilder sb = new StringBuilder();
        
        dfs(res, digits, sb, map);
        
        return res;
    }

    private void dfs(ArrayList<String> res, String digits, StringBuilder sb, HashMap<Character, char[]> map) {
        if(digits.length() == sb.length())
        {
            res.add(sb.toString());
            return;
        }
        
        for(char c : map.get(digits.charAt(sb.length()))) {
            sb.append(c);
            dfs(res, digits, sb, map);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档