leetcode017 Letter Combinations of a Phone Number

題目

17. Letter Combinations of a Phone Number
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.
image

Input:Digit string "23" 
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:

利用遞歸求解。

代碼:

private List<String> out = new ArrayList<>();

private List<String> in = new ArrayList<>();

private String[] resources = {"", "", "abc", "def", "ghi", "jkl", "mon", "pqrs", "tuv", "wxyz"};



public List<String> letterCombinations(String digits)

{

    if(digits == null || digits.length() == 0 || digits.contains("1") || digits.contains("0"))

        return out;

    char[] c_digits = digits.toCharArray();

    for(char c_digit : c_digits) in.add(resources[c_digit - '0']);

    getString("", 0);

    return out;

}



private void getString(String builder, int index)

{

    char[] chars = in.get(index).toCharArray();

    if(index == in.size() - 1)

        for(char c : chars)

            out.add(builder + c);

    else

        for(char aChar : chars)

            getString(builder + aChar, index + 1);

}

結果細節(圖):

image

發佈了44 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章