zoukankan      html  css  js  c++  java
  • Letter Combinations of a Phone Number

    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.

    参考:http://www.cnblogs.com/tgkx1054/p/3298501.html

    度娘过后,发现很多人用的都是dfs递归实现的,当然直接贴代码的还是很多,我也是这样的。

     1 import java.util.ArrayList;
     2 import java.util.Arrays;
     3 import java.util.List;
     4 
     5 public class Solution {
     6     List<String> result = new ArrayList<String>();
     7     String dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
     8     String path = "";
     9     
    10     public List<String> letterCombinations(String digits) {
    11         dfs(digits);
    12         
    13         return result;
    14     }
    15     
    16     /**
    17      * 这里用dfs来解决
    18      * @param dep
    19      * @param digits
    20      */
    21     public void dfs(String digits){
    22         if(digits.length() == 0){
    23             result.add(path);
    24         }else{
    25             for(int i = 0; i < dict[digits.charAt(0) - '0'].length(); i++){
    26                 path += dict[digits.charAt(0) - '0'].charAt(i);
    27                 dfs(digits.substring(1, digits.length()));
    28                 path = path.substring(0, path.length() - 1);
    29             }
    30         }
    31     }
    32 }
  • 相关阅读:
    AtomicReference与volatile的区别
    深度剖析ConcurrentHashMap(转)
    ConcurrentHashMap原理分析
    Java Stack源码分析
    Fail-Fast机制详解
    TreeSet源码分析
    状态(State)模式
    原型(Prototype)模式
    职责连模式
    观察者模式(Observer)
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4154109.html
Copyright © 2011-2022 走看看