zoukankan      html  css  js  c++  java
  • leetcode : Letter Combinations of 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"].
    

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

    思路: 深度优先, 回溯

    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> result = new ArrayList<String>();
            if(digits == null || digits.length() == 0) {
                return result;
            }
           
            Map<Character,char[]> map = new HashMap<Character, char[]>();
            map.put('1', new char[]{});
            map.put('2', new char[]{'a', 'b', 'c'});
            map.put('3', new char[]{'d', 'e', 'f'});
            map.put('4', new char[]{'g', 'h' , 'i'});
            map.put('5', new char[] { 'j', 'k', 'l' });
            map.put('6', new char[] { 'm', 'n', 'o' });
            map.put('7', new char[] { 'p', 'q', 'r', 's' });
            map.put('8', new char[] { 't', 'u', 'v'});
            map.put('9', new char[] { 'w', 'x', 'y', 'z' });
             StringBuilder sb = new StringBuilder();
             helper(result, digits, map, sb);
             return result;
        }
        
        public void helper(List<String> result, String digits, Map<Character, char[]> map, StringBuilder sb) {
            if(sb.length() == digits.length()) {
                result.add(sb.toString());
                return;
            }
            
            for(char c : map.get(digits.charAt(sb.length()))) {
                sb.append(c);
                helper(result, digits, map, sb);
                sb.deleteCharAt(sb.length() - 1);
            }
            
        }
    }
    
  • 相关阅读:
    memcached客户端memadmin安装使用
    git之一: 在windows下安装git和使用总结
    nginx常用命令
    mysql授权 REVOKE 添加用户等
    mysql密码忘记解决
    个人常用alias
    解决zabbix图形界面中文乱码
    JsonPath的使用
    Httpclient 支持https(转)
    字符串拼接‘+’实现
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6396015.html
Copyright © 2011-2022 走看看