LeetCode 17. Letter Combinations of a Phone Number(递归)

题目来源:https://leetcode.com/problems/letter-combinations-of-a-phone-number/

问题描述

17. Letter Combinations of a Phone Number

Medium

Given a string containing digits from 2-9inclusive, 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.

http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png

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.

------------------------------------------------------------

题意

给出九宫格按键图和一组按键序列,求该按键序列可能对应的所有字符串

------------------------------------------------------------

思路

用HashMap或二维数组或一个静态方法表示按键的映射关系,递归计算所有可能的字符串

本文用的是静态HashMap,初始化的时候用到了静态块。另一种更简洁的方法是用匿名内部类的初始化:

public static final HashMap<Character, 
List<Character>> keyMap = new HashMap<Character, List<Character>>(){
{
    put('2', Arrays.asList('a', 'b', 'c'));
    put('3', Arrays.asList('d', 'e', 'f'));
    put('4', Arrays.asList('g', 'h', 'i'));
    put('5', Arrays.asList('j', 'k', 'l'));
    put('6', Arrays.asList('m', 'n', 'o'));
    put('7', Arrays.asList('p', 'q', 'r', 's'));
    put('8', Arrays.asList('t', 'u', 'v'));
    put('9', Arrays.asList('w', 'x', 'y', 'z'));
    }
};
    

而List的初始化用到了Arrays.asList

------------------------------------------------------------

代码

class Solution {
    public static final HashMap<Character, 
List<Character>> keyMap = new HashMap<Character, List<Character>>();
    static {
        keyMap.put('2', Arrays.asList('a', 'b', 'c'));
        keyMap.put('3', Arrays.asList('d', 'e', 'f'));
        keyMap.put('4', Arrays.asList('g', 'h', 'i'));
        keyMap.put('5', Arrays.asList('j', 'k', 'l'));
        keyMap.put('6', Arrays.asList('m', 'n', 'o'));
        keyMap.put('7', Arrays.asList('p', 'q', 'r', 's'));
        keyMap.put('8', Arrays.asList('t', 'u', 'v'));
        keyMap.put('9', Arrays.asList('w', 'x', 'y', 'z'));
    }
    
    public List<String> letterCombinations(String digits) {
        int n = digits.length(), i = 0;
        if (n == 0)
        {
            return new LinkedList<String>();
        }
        List<String> pret = new LinkedList<String>(){
            {
                add("");
            }
        }; 
        for (i = 0; i < n; i++)
        {
            List<String> ret = new LinkedList<String>();
            for (String str: pret)
            {
                List<Character> clist = keyMap.get(digits.charAt(i));
                for (Character ch: clist)
                {
                    ret.add(str + ch);
                }
            }
            pret = ret;
        }
        return pret;
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/88364141