• 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);
                    }
                }
            }
        }
    
    
    }
  • 相关阅读:
    Java + Element-UI 实现简单的树形菜单
    简单了解一下 Nginx
    使用阿里云 OSS 存储、访问图片(Java)
    JSR 303 进行后台数据校验
    SpringBoot 常用注解
    12、js——轮播图
    11、js——定时调用和延时调用
    11、js——BOM
    10、js——事件
    9、js——样式相关的操作
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4395968.html
Copyright © 2020-2023  润新知