• leetcode17


    17. Letter Combinations of a Phone Number
    Medium
    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

    A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

    Example:

    Input: "23"
    Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

    解答:

    class Solution {
        public List<String> letterCombinations(String digits) {
            String[] table = new String[]{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
            List<String> list = new ArrayList<>();
            
            letterCombinations(list, digits, "", 0, table);
            
            return list;
        }
        
        private void letterCombinations(List<String> list, String digits, String curr, int index, String[] table) {
            // 最后一层退出条件
            if(index == digits.length()) {
                if(curr.length() != 0) {
                    list.add(curr);
                }
                
                return;
            }
            
            String temp = table[digits.charAt(index)-'0'];
            
            for(int i = 0; i < temp.length(); i++) {
                String next = curr + temp.charAt(i);
                // 进入下一层
                letterCombinations(list, digits, next, index+1, table);
            }
        }
    }
    

      

    经典的backtracking(回溯算法)的题目。当一个题目,存在各种满足条件的组合,并且需要把它们全部列出来时,就可以考虑backtracking了。当然,backtracking在一定程度上属于穷举,所以当数据特别大的时候,不合适。而对于那些题目,可能就需要通过动态规划来完成。

      这道题的思路很简单,假设输入的是"23",2对应的是"abc",3对应的是"edf",那么我们在递归时,先确定2对应的其中一个字母(假设是a),然后进入下一层,穷举3对应的所有字母,并组合起来("ae","ad","af"),当"edf"穷举完后,返回上一层,更新字母b,再重新进入下一层。这个就是backtracing的基本思想。

    https://www.cnblogs.com/kepuCS/p/5271654.html

  • 相关阅读:
    FFmpeg简单使用:解封装 ---- 基本流程
    SDL播放PCM音频数据
    JDK8时间新API-2
    RocketMq延时队列的实现原理
    Kibana复杂查询语句
    Es基础api
    Redis sscan命令
    如何实现分布式的延时队列
    客户端从broker拉取的messagequeue的样子
    RocketMq多个consumerQueue长什么样子
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10732572.html
Copyright © 2020-2023  润新知