zoukankan      html  css  js  c++  java
  • 电话号字母组合,利用深度搜索的思想。

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

     1 import java.util.ArrayList;
     2 import java.util.List;
     3 
     4 public class test
     5 {
     6           List<String> res;
     7         public List<String> letterCombinations(String digits) {
     8             String[] table = {"","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
     9             char[] temp = new char[digits.length()];
    10             res = new ArrayList<String>();
    11             helper(table, 0, temp, digits);
    12             return res;
    13         }
    14         
    15         public void helper(String[] table, int index, char[] temp, String digits)
    16         {
    17             if(index == digits.length())
    18             {
    19                 if(temp.length!=0)//判断,不然A不过去。
    20                 {
    21                     res.add(new String(temp));
    22                 }
    23             }
    24             else
    25             {
    26                 String candidates = table[digits.charAt(index)-'0'];//候选字母表
    27                 for(int i = 0; i < candidates.length(); i ++)
    28                 {
    29                     temp[index] = candidates.charAt(i);
    30                     helper(table, index + 1, temp, digits);//深度遍历digits
    31                 }
    32             }
    33         }
    34         
    35         public static void main(String[] args)
    36         {
    37             test t = new test();
    38             System.out.println(t.letterCombinations("23"));
    39         }
    40 }
  • 相关阅读:
    剑指offer——最小的K个数和数组中第K大的元素
    Leetcode刷题指南链接整理
    160. Intersection of Two Linked Lists
    100. Same Tree
    92. Reverse Linked List II
    94. Binary Tree Inorder Traversal
    79. Word Search
    78,90,Subsets,46,47,Permutations,39,40 DFS 大合集
    0x16 Tire之最大的异或对
    0x16 Tire
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5535805.html
Copyright © 2011-2022 走看看