• 【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 }
  • 相关阅读:
    从BATS交易所获取空头头寸
    用cython提升python的性能
    用Python编写的第一个回测程序
    Omi框架学习之旅
    Omi框架学习之旅
    AlloyTouch.js 源码 学习笔记及原理说明
    AlloyFinger.js 源码 学习笔记及原理说明
    Git 学习笔记
    从数组中每次取一个不同的数组成员 getRandomItem(arr)
    move.js 源码 学习笔记
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3836489.html
Copyright © 2020-2023  润新知