1. 程式人生 > 其它 >17 電話號碼的字母組合(LeetCode HOT 100)

17 電話號碼的字母組合(LeetCode HOT 100)

描述:
給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。答案可以按 任意順序 返回。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。

示例 1:

輸入:digits = "23"
輸出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

輸入:digits = ""
輸出:[]

示例 3:

輸入:digits = "2"
輸出:["a","b","c"]

提示:
0 <= digits.length <= 4
digits[i] 是範圍 ['2', '9'] 的一個數字。

Soulution:

public static void main(String[] args) {
        // [ad, ae, af, bd, be, bf, cd, ce, cf]
        System.out.println(letterCombinations("23"));
        // []
        System.out.println(letterCombinations(""));
        // [a, b, c]
        System.out.println(letterCombinations("2"));

    }

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

    public static List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        if (digits.length() <= 0) {
            return result;
        }
        // 遞迴
        findNextLetter(result, digits.toCharArray(), 0, "");
        return result;
    }

    private static void findNextLetter(List<String> result, char[] digits, int index, String tempStrBd) {
        if (digits.length == index) {
            result.add(tempStrBd);
            return;
        }
        // 取出對應字元
        String[] strings = numToLetterMap.get(digits[index]);
        for (String string : strings) {
            String temp = tempStrBd + string;
            findNextLetter(result, digits, index + 1, temp);
        }
    }

Idea:
遞迴,雖然時間複雜度沒有很低,但程式碼優雅

Reslut: