zoukankan      html  css  js  c++  java
  • Letter Combinations of a Phone Number——LeetCode

    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.

    题目大意:给一组数字,按照电话键盘上的组合输出所有的可能。

    解题思路:直接递归写DFS,输出所有组合。

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    public class LetterCombinationsofaPhoneNumber {
    
        public static void main(String[] sure) {
            new LetterCombinationsofaPhoneNumber().letterCombinations("213");
        }
    
        static Map<Character, String> mapping = new HashMap<>();
    
        static {
            mapping.put('0', "");
            mapping.put('1', "");
            mapping.put('2', "abc");
            mapping.put('3', "def");
            mapping.put('4', "ghi");
            mapping.put('5', "jkl");
            mapping.put('6', "mno");
            mapping.put('7', "pqrs");
            mapping.put('8', "tuv");
            mapping.put('9', "wxyz");
        }
    
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            if (digits == null || digits.length() == 0) {
                return res;
            }
            combine(digits, "", res, digits.length());
            System.out.println(res);
            return res;
        }
    
        private void combine(String digits, String tmp, List<String> res, int length) {
            if (length == 0) {
                res.add(tmp);
                return;
            }
            for (int i = 0; i < digits.length(); i++) {
                String val = mapping.get(digits.charAt(i));
                if ("".equals(val)) {
                    combine(digits.substring(i + 1), tmp, res, length - 1);
                } else {
                    for (char c : val.toCharArray()) {
                        combine(digits.substring(i + 1), tmp + c, res, length - 1);
                    }
                }
            }
        }
    
    
    }
  • 相关阅读:
    Linux:Day7(上) find、文件特殊权限、if语句
    Linux:Day6(下) vim编辑器
    Linux:Day6(上) egrep、条件测试
    Linux:Day5 shell编程初步、grep
    Linux:Day4(下) 用户及组管理
    Linux中的cat、more、less、head、tail命令
    ajax中的contendType和dataType知识点梳理
    Django使用jsonp和cors解决跨域请求问题
    Django的Modelforms的介绍
    Django的Rbac介绍3
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4395968.html
Copyright © 2011-2022 走看看