zoukankan      html  css  js  c++  java
  • 17. Letter Combinations of a Phone Number

    Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

    Example:

    Input: "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.

    use DFS: n recursion levels, in each recursion level, there're at most 4 states to consider about

    time = O(4 ^ n), space = O(n)

    class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            if(digits.length() == 0) {
                return res;
            }
            String[] keypads = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            dfs(digits, 0, keypads, new StringBuilder(), res);
            return res;
        }
        
        public void dfs(String s, int idx, String[] keypads, StringBuilder sb, List<String> res) {
            if(idx == s.length()) {
                res.add(sb.toString());
                return;
            }
            int cur = Integer.parseInt(s.substring(idx, idx + 1));
            for(int i = 0; i < keypads[cur].length(); i++) {
                sb.append(keypads[cur].charAt(i));
                dfs(s, idx + 1, keypads, sb, res);
                sb.deleteCharAt(sb.length() - 1);
            }
        }
    }
  • 相关阅读:
    mysql问题: alter导致速度慢
    MySQL的mysql_insert_id和LAST_INSERT_ID
    linux动态链接库---一篇讲尽
    jsoncpp第二篇------API
    SVN第二篇-----命令集合
    svn第一篇----入门指南
    数据结构之堆
    SZU4
    SZU1
    SZU2
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11319370.html
Copyright © 2011-2022 走看看