17. 电话号码的字母组合 ( 递归 + 哈希表 )

LeetCode:17. 电话号码的字母组合

在这里插入图片描述

每个按键( 一个数字 ) 对应着多个字母,全排列, 递归 dfs


利用 哈希表 存储每个键位都有些啥字母


AC Code

class Solution {
    
    

    public void init(Map<Integer, char[]> map){
    
    
        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'});
    }

    List<String> list = new ArrayList<>();
    Map<Integer, char[]> map = new HashMap<>();
    public List<String> letterCombinations(String digits) {
    
    
        if("".equals(digits)) return list;
        init(map);
        char[] cs = digits.toCharArray();
        dfs(cs, 0, "");
        return list;
    }

    public void dfs(char[] cs, int s, String str){
    
    
        if(s >= cs.length) {
    
    
            list.add(str);
            return ;
        }
        
        char [] c = map.get(cs[s] - '0');
        int len = c.length;
        for(int i = 0; i < len; i++) {
    
    
            // 遍历所有的字母
            dfs(cs, s + 1, str + c[i]);
        }       
    }

}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/112832272