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.git

A mapping of digit to letters (just like on the telephone buttons) is given below.app

Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf","cd", "ce", "cf"]. Note: Although the above answer is lexicographical order, your answer could be in any order you want.函數

思路: 經典的backtracking解法。用HashMap存儲數字對應的字母。而後就像subsets 同樣。 這種題型都要利用返回void的helper函數,而後判斷在什麼條件的時候加入result中,而後在循環裏面加入,遞歸再刪除。對於這道題目, 當新生成的string的長度和digits的長度同樣的時候就加入result裏面。 而後for循環可能的char, 就是每一個數字對應的char[]裏的元素。 ui

注意幾點: string須要刪減的時候用StringBuilder. 學一下如何新建帶初始值的array。 code

時間複雜度:假設總共有n個digit,每一個digit能夠表明k個字符,那麼時間複雜度是O(k^n),就是結果的數量,因此是O(3^n)
空間複雜度:O(n)遞歸

public class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if (digits == null || digits.length() == 0) {
            return result;
        }
        HashMap<Character, char[]> hash = new HashMap<Character, char[]>();
        hash.put('0', new char[]{});
        hash.put('1', new char[]{});
        hash.put('2', new char[] { 'a', 'b', 'c' });
        hash.put('3', new char[] { 'd', 'e', 'f' });
        hash.put('4', new char[] { 'g', 'h', 'i' });
        hash.put('5', new char[] { 'j', 'k', 'l' });
        hash.put('6', new char[] { 'm', 'n', 'o' });
        hash.put('7', new char[] { 'p', 'q', 'r', 's' });
        hash.put('8', new char[] { 't', 'u', 'v'});
        hash.put('9', new char[] { 'w', 'x', 'y', 'z' });
        
        StringBuilder s = new StringBuilder();
        helper(result, hash, s, digits,0);
        return result;
    }
    private void helper(List<String> result, HashMap<Character, char[]> hash, StringBuilder s, String digits, int i ) {
        if (digits.length() == s.length()) {
            result.add(s.toString());
            return;
        }
        for (char c : hash.get(digits.charAt(i)) ) {
            s.append(c);
            helper(result,hash,s, digits, i + 1);
            s.deleteCharAt(s.length() - 1);
        }
    }
}
相關文章
相關標籤/搜索