zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】Letter Combinations of a Phone Number

    Given a digit string, 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.

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

    Note:
    Although the above answer is in lexicographical order, your answer could be in any order you want.


    题解:用一个二维数组map保存数字到字母的映射,然后深度优先递归搜索如下的一棵树(以"23"为例,树不完整)

    代码如下:

     1 public class Solution {
     2     public List<String> letterCombinations(String digits) {
     3         ArrayList<String> answer = new ArrayList<String>();
     4         
     5         char[][] map = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
     6         String currentPath = new String();
     7         
     8         DeepSearch(map, answer, digits, currentPath);
     9         return answer;
    10     }
    11     
    12     public void DeepSearch(char[][] map,List<String> answer,String digits,String currentPath){
    13         if(digits.length() == 0)
    14         {
    15             String temp = new String(currentPath);
    16             answer.add(temp);
    17 
    18             return;
    19         }
    20         
    21         int now = digits.charAt(0) - '0';
    22         for(int j = 0;j < map[now-2].length;j++){
    23             currentPath += map[now-2][j];
    24             DeepSearch(map, answer, digits.substring(1), currentPath);
    25             currentPath = currentPath.substring(0, currentPath.length()-1);
    26         }
    27     }
    28 }
  • 相关阅读:
    SharePoint 2013 中的 URL 和标记
    负载均衡
    高可用集群
    客户端访问浏览器的流程
    【SDOI2014】数表
    【UR #5】怎样跑得更快
    【BZOJ2820】YY的GCD
    【SDOI2017】数字表格
    Codeforces 548E Mike ans Foam (与质数相关的容斥多半会用到莫比乌斯函数)
    【BZOJ2693】jzptab
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3836489.html
Copyright © 2011-2022 走看看