LeetCode 17. Letter Combinations of a Phone Number (电话号码的字母组合)

Posted 几米空间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 17. Letter Combinations of a Phone Number (电话号码的字母组合)相关的知识,希望对你有一定的参考价值。

题目标签:Backtracking

  建立一个hashmap 把数字 对应 字母 存入 map;

  利用dfs,每次存入一个 char,当 chars 达到 digtis 的size 返回,具体看code。

  

 

Java Solution: 

Runtime:  0 ms, faster than 100.00 % 

Memory Usage: 38.7 MB, less than 6.16 %

完成日期:12/15/2019

关键点:HashMap

class Solution {
    
    List<String> res;
    HashMap<Character, String> map;
    
    public List<String> letterCombinations(String digits) {
        res = new ArrayList<>();
        map = new HashMap<>();
        StringBuilder comb = new StringBuilder();
        
        if(digits.length() == 0)
            return res;
        
        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");
        
        DFS(digits, 0, comb);
        
        return res;
    }
    
    
    private void DFS(String digits, int pos, StringBuilder comb) {
        if(pos == digits.length()) {
            res.add(comb.toString());
            return;
        } 
        
        // go through each char
        for(char c : map.get(digits.charAt(pos)).toCharArray()) {
            comb.append(c);
            DFS(digits, pos+1, comb);
            comb.deleteCharAt(comb.length()-1);
        }
        
            
    }
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

以上是关于LeetCode 17. Letter Combinations of a Phone Number (电话号码的字母组合)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题python解法:17. Letter Combinations of a Phone Number

Leetcode 17.——Letter Combinations of a Phone Number

LeetCode-17-Letter Combinations of a Phone Number

LeetCode17. Letter Combinations of a Phone Number

LeetCode17:Letter Combinations of a Phone Number

[LeetCode] 17. Letter Combinations of a Phone Number