zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    c#创建对象并动态添加属性
    js从$scope外部调用$scope内部函数,跨js调用非全局函数
    JQuery中$.ajax()方法参数详解
    c#关于int(或其他类型)的字段在对象初始化时默认初始化问题的解决方法
    SQLServer中存储过程StoredProcedure创建及C#调用(转)
    2020年将热门的8大IT职业领域
    2015总结+2016计划
    hadoop程序在本地模式调试作业
    Flume+Kafka+storm的连接整合
    scp 和 pscp
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10732572.html
Copyright © 2011-2022 走看看