• 17. *的字母组合-dfs-中等难度


    问题描述

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

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

     

    示例:

    输入:"23"
    输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
    说明:
    尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number

    题解

    //dfs,和八皇后那道题很像
    class Solution {
        Map<Integer, String> m;
        public void dfs(List<String> res, String digits, StringBuilder temp, int len, int deep, int index){
            if(deep == 0 && index == m.get((int)(digits.charAt(deep)-'0')).length())return;
    
            if(index == m.get((int)(digits.charAt(deep)-'0')).length()){
                //回到上一层
                int pre_index = m.get((int)(digits.charAt(deep-1)-'0')).indexOf(temp.charAt(temp.length()-1));
                temp.deleteCharAt(temp.length()-1);//删除最后一位
                dfs(res, digits, temp, len, deep-1, pre_index+1);
                return;
            }
            if(deep != len-1){
                temp.append(m.get((int)(digits.charAt(deep)-'0')).charAt(index));
                dfs(res, digits, temp, len, deep+1, 0);//去下一层
            }
            else{
                temp.append(m.get((int)(digits.charAt(deep)-'0')).charAt(index));
                res.add(temp.toString());
                temp.deleteCharAt(temp.length()-1);//删除最后一位
                dfs(res, digits, temp, len, deep, index+1);//去同层的右边
                return;
            }
        }
        public List<String> letterCombinations(String digits) {
            m = new HashMap<Integer, String>();
            m.put(2,"abc");
            m.put(3,"def");
            m.put(4,"ghi");
            m.put(5,"jkl");
            m.put(6,"mno");
            m.put(7,"pqrs");
            m.put(8,"tuv");
            m.put(9,"wxyz");
            int len = digits.length();
            List<String> res = new LinkedList<String>();
            if(len == 0)return res;
            dfs(res, digits, new StringBuilder(), len, 0, 0);
            return res;
        }
    }
  • 相关阅读:
    repair table
    rmtree函数
    alias 新的命令='原命令 -选项/参数'。举例说明,alias l=‘ls -lsh' 将重新定义 ls 命令,现在只需输入 l 就可以列目录了。
    MySQL DATE_SUB() 函数
    freebsd开启root远程登陆
    nbtscan ip地址
    FreeBSD 安裝 wget
    genlist -s 192.168.21.*
    /pentest/enumeration/0trace
    CSS的margin属性:详解margin属性
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13346058.html
Copyright © 2020-2023  润新知