• 【leetcode】17. Letter Combinations of a Phone Number


    题目描述:

    Given a digit string, return all possible letter combinations that the number could represent.

    解题分析:

    回溯法的典型应用,用一个数据结构表示出按键与其表示字母的对应关系,直接用回溯法做即可。

    具体代码:

     1 public class Solution {
     2     private static List<String> results=new ArrayList<String>();
     3     private static String[] array= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
     4     public static List<String> letterCombinations(String digits) {
     5             //String[] array= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
     6             results=new ArrayList<String>();
     7             if(digits==null||digits.length()==0)
     8                 return results;
     9             StringBuilder sb = new StringBuilder();
    10             
    11             fun(digits,sb,0);
    12             return results;
    13     }
    14 
    15     private static void fun(String digits, StringBuilder sb,
    16             int i) {
    17         if(i==digits.length()-1){
    18             char ch = digits.charAt(i);
    19             int index = ch-'0';
    20             for(int j=0;j<array[index].length();j++){
    21                 sb.append(array[index].charAt(j));
    22                 results.add(sb.toString());
    23                 sb.deleteCharAt(sb.length()-1);
    24             }
    25             return;
    26         }
    27         char ch = digits.charAt(i);
    28         int index = ch-'0';
    29         for(int j=0;j<array[index].length();j++){
    30             sb.append(array[index].charAt(j));
    31             fun(digits, sb, i+1);
    32             sb.deleteCharAt(sb.length()-1);
    33         }
    34     }
    35 }
  • 相关阅读:
    -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HOME environment variable and mvn script match.chan
    failed to export application
    IOS InHouse 发布流程
    BoneCP学习笔记
    form表单, css1
    HTTP协议, HTML
    自定义ORM框架
    数据库5
    数据库4
    数据库3
  • 原文地址:https://www.cnblogs.com/godlei/p/5642142.html
Copyright © 2020-2023  润新知