[LeetCode]Letter Combinations of a Phone Number

发表于
2

题目传送门

题目理解:给定一个字符串(字符串内容由2-9的数字组成),需要计算出这个字符串按照9键输入法打字,可能打出的所有可能的词组(可以是无意义的词,并不要求是单词),返回结果不强制固定顺序,只要包含全部结果就可以。

思路:利用递归,将digits(输入的字符串)、index(当前递归到的索引)、lastArray(上次递归的结果数组)作为参数,index == digits.length()作为结束条件。

代码:

class Solution {
    private static final String[][] numberMap = new String[10][];

    static {
        numberMap[0] = new String[]{""};
        numberMap[1] = new String[]{""};
        numberMap[2] = new String[]{"a", "b", "c"};
        numberMap[3] = new String[]{"d", "e", "f"};
        numberMap[4] = new String[]{"g", "h", "i"};
        numberMap[5] = new String[]{"j", "k", "l"};
        numberMap[6] = new String[]{"m", "n", "o"};
        numberMap[7] = new String[]{"p", "q", "r", "s"};
        numberMap[8] = new String[]{"t", "u", "v"};
        numberMap[9] = new String[]{"w", "x", "y", "z"};
    }

    public List<String> letterCombinations(String digits) {
        return getResult(digits, 0, new ArrayList<>());
    }

    public List<String> getResult(String digits, int index, List<String> lastArray) {
        if (index == digits.length()) {
            return lastArray;
        }
        int number = digits.charAt(index) - '0';
        String[] letterArr = numberMap[number];
        List<String> nowArray = new ArrayList<>();
        for (String s : letterArr) {
            if (!lastArray.isEmpty()) {
                for (String string : lastArray) {
                    nowArray.add(string + s);
                }
            } else {
                nowArray.add(s);
            }
        }
        return getResult(digits, index + 1, nowArray);
    }
}


0
上一篇 记录死锁问题