zoukankan      html  css  js  c++  java
  • 【LeetCode】18.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"].

    递归的题老是做不好。拿到此题一直纠结于字母与数字的关系,可以再怎么纠结,也是得一个个遍历才可以。用DFS,注意if(ans.size()==0) ans.add("");

    public class Solution {
         public ArrayList<String> letterCombinations(String digits) {
             ArrayList<String> ans = new ArrayList<String>();
             ArrayList<Character> chars = new ArrayList<Character>();
             HashMap<Character,String> map = new HashMap<Character,String>();
             init(map);
             dfs(map,digits,0,chars,ans);
             if(ans.size()==0)
                 ans.add("");
             return ans;
         }
         private void dfs(HashMap<Character, String> map, String digits, int idx, ArrayList<Character> chars, ArrayList<String> arr){
             if(idx >= digits.length()) return;
             char c = digits.charAt(idx);
             String s = map.get(c);
             for(int i = 0; i<s.length();i++){
                 if(idx == digits.length()-1){
                     chars.add(s.charAt(i));
                     StringBuilder sb = new StringBuilder();
                     for(char cc: chars){
                         sb.append(cc);
                     }
                     arr.add(sb.toString());
                     chars.remove(chars.size()-1);
                 }else{
                     chars.add(s.charAt(i));
                     dfs(map,digits,idx+1,chars,arr);
                     chars.remove(chars.size()-1); //char.remove(index)
                 }
             }
         }
          
         private void init(HashMap<Character,String> map){
             map.put('1', "");
             map.put('2', "abc");
             map.put('3', "def");
             map.put('4', "ghi");
             map.put('5', "jkl");
             map.put('6', "mno");
             map.put('7', "pqrs");
             map.put('8', "tuv");
             map.put('9', "wxyz");
         }
    }
  • 相关阅读:
    msql查询指定日期
    NLP常见任务
    KTT条件及其理解
    距离度量--熵,KL散度,JS散度,GAN相关应用
    常见的激活函数
    分类问题的判别标准
    最大似然估计
    损失函数
    【ML-10】多分类及多标签分类算法
    【ML-9】支持向量机--实验scitit-learn SVM
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3402062.html
Copyright © 2011-2022 走看看