zoukankan      html  css  js  c++  java
  • LeetCode回溯系列(1)——第17题解法

    题目描述:

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

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

     

    示例:

    输入:"23"
    输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

    解题思路:

      给出如下回溯函数 backtrack(combination, next_digits) ,它将一个目前已经产生的组合 combination 和接下来准备要输入的数字 next_digits 作为参数。

    • 如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
    • 如果还有数字需要被输入:

        遍历下一个数字所对应的所有映射的字母。
        将当前的字母添加到组合最后,也就是 combination = combination + letter 。

    • 重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:]) 。

    Java代码:

    class Solution {
      Map<String, String> phone = new HashMap<String, String>() {{
        put("2", "abc");
        put("3", "def");
        put("4", "ghi");
        put("5", "jkl");
        put("6", "mno");
        put("7", "pqrs");
        put("8", "tuv");
        put("9", "wxyz");
      }};
    
      List<String> output = new ArrayList<String>();
    
      public void backtrack(String combination, String next_digits) {
        // if there is no more digits to check
        if (next_digits.length() == 0) {
            // the combination is done
            output.add(combination);
        }
        // if there are still digits to check
        else {
            // iterate over all letters which map 
            // the next available digit
            String digit = next_digits.substring(0, 1);
            String letters = phone.get(digit);
            for (int i = 0; i < letters.length(); i++) {
              String letter = phone.get(digit).substring(i, i + 1);
              // append the current letter to the combination
              // and proceed to the next digits
              backtrack(combination + letter, next_digits.substring(1));
            }
          }
      }
    
      public List<String> letterCombinations(String digits) {
        if (digits.length() != 0)
          backtrack("", digits);
        return output;
      }
    }

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 相关阅读:
    阮一峰的网络日志 算法
    Problem 2184 逆序数还原
    vs项目中使用c++调用lua
    多例模式
    关于O_APPEND模式write的原子性
    清醒
    编译时,遇到Couldn&#39;t build player because of unsupported data on target platform的解决方式
    把JavaScript和CSS放到外部文件里
    SSM框架——具体整合教程(Spring+SpringMVC+MyBatis)
    MMORPG网页游戏斩仙录全套源代码(服务端+client)
  • 原文地址:https://www.cnblogs.com/SupremeBoy/p/12275723.html
Copyright © 2011-2022 走看看