LeetCode 17—— 回溯

給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。

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

  • 示例:

    輸入:“23”
    輸出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

說明:儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。

class Solution {
    Map<String, String> phone = new HashMap<String, String>() {{
            put("2", "abc");
            put("3", "def");
            put("4", "ghi");
            put("5", "jkl");
            put("6", "mno");
            put("7", "pqrs");
            put("8", "tuv");
            put("9", "wxyz");
    }};
    List<String> output = new ArrayList<String>();
    
    public void backtrack(String combination, String  next_digits){
        if (next_digits.length() == 0){
            output.add(combination);
        }else {
            String digit = next_digits.substring(0, 1);
            String letters = phone.get(digit);
            for (int i = 0; i < letters.length(); i++) {
                String letter = phone.get(digit).substring(i, i+1);

                // 將當前字符與“上層”字符相拼接
                // 並且與下一個數字進行關聯
                backtrack(combination + letter, next_digits.substring(1));
            }
        }
    }
    public List<String> letterCombinations(String digits){
        if (digits.length() != 0)
            backtrack("", digits);
        return output;
    }
}

執行用時 :2 ms, 在所有 Java 提交中擊敗了69.92%的用戶
內存消耗 :36.2 MB, 在所有 Java 提交中擊敗了73.14%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章