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");
         }
    }
  • 相关阅读:
    观察者模式-Observer
    @Resource、@Autowired、@Qualifier的注解注入及区别
    Java垃圾回收(GC)机制详解
    java什么时候进行垃圾回收,垃圾回收的执行流程
    Log4J.xml配置详解
    springMVC配置拦截器、过滤器、前端控制器时遇到的问题总结
    基于zookeeper实现分布式锁
    数据库索引原理及优化
    数据分析——CentOS7配置时间和ntp
    solr——zookeeper部署
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3402062.html
Copyright © 2011-2022 走看看