zoukankan      html  css  js  c++  java
  • [LC] 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.

    Time: O(3^N)

    class Solution {
        private String[] letters = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            if (digits == null || digits.length() == 0) {
                return res;
            }
            helper(res, "", digits, 0);
            return res;
        }
        
        private void helper(List<String> res, String s, String digits, int index) {
            if (s.length() == digits.length()) {
                res.add(s);
                return;
            }
            String curLetter = letters[digits.charAt(index) - '0'];
            // loop through current letters[index] 
            for (int i = 0; i < curLetter.length(); i++) {
                helper(res, s + curLetter.charAt(i), digits, index + 1);
            }
        }
    }
  • 相关阅读:
    设计模式之单例模式实践
    有关集合的foreach循环里的add/remove
    项目中常用的MySQL优化方法--壹拾玖条
    Solr
    Lucene补充
    Lucene
    一千行 MySQL 学习笔记
    Servlet
    CSS未知宽高元素水平垂直居中
    深拷贝和浅拷贝
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11975764.html
Copyright © 2011-2022 走看看