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

    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"].
    

    Note:

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

     1 class Solution {
     2     public char [][] dist;
     3     public int []num;
     4     public void dfs(char[] now, int pos, List<String> ans, String digits) {
     5         if (pos == digits.length()) {
     6             char[] temp = new char[pos];
     7             for (int i = 0; i < pos; ++i)
     8                 temp[i] = now[i];
     9             ans.add(String.valueOf(temp));
    10             return;
    11         }
    12         char c = digits.charAt(pos);
    13         int id = c - '2';
    14         for (int i = 0; i < num[id]; ++i) {
    15             now[pos] = dist[id][i];
    16             dfs(now, pos + 1, ans, digits);
    17         }
    18         
    19         
    20     }
    21     
    22     public void init() {
    23         int []temp = new int[]{3, 3, 3, 3, 3, 4, 3, 4};
    24         dist = new char[8][5];
    25         int sum = 0;
    26         for (int i = 0; i < 8; ++i) {
    27             sum += i== 0 ? 0 : temp[i - 1];
    28             for (int j = 0; j < temp[i]; ++j) {
    29                 dist[i][j] = (char)(j  + 97 + sum);
    30             }
    31         }
    32         num = temp;
    33     }
    34     public List<String> letterCombinations(String digits) {
    35         List<String> ans = new ArrayList<>();
    36         if (digits.length() == 0) return ans;
    37         int n = digits.length();
    38         char []now = new char[n + 1];
    39         init();
    40        
    41         
    42         dfs(now, 0, ans, digits);
    43         return ans;
    44     }
    45 }
  • 相关阅读:
    使用pthread_create时参数的传递
    借用 Google 构建自己的搜索系统
    编辑Servlet程序
    线程简单介绍
    Apache Tomcat服务器配置基础
    win2000server IIS和tomcat5多站点配置
    COmega 概述
    用Flash制作Google搜索程序
    浅析.Net下的多线程编程
    Mozilla宣布XForms开发项目 XForms是什么?它带来了什么?
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12304749.html
Copyright © 2011-2022 走看看