leetcode_[python/C++] 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.
這裏寫圖片描述

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

Subscribe to see which companies asked this question


【分析】
思路:
1)遞歸
2)循環迭代
注意的點就是當輸入爲“”時,返回[ ]
當輸入爲“0”之類的還需要範圍[“”]


遞歸
遞歸的寫法有兩種,一種是一個函數裏面的遞歸寫法,一種是引用另外的函數的寫法
先貼下自己的代碼,也就是第二種

class Solution {
public:
    vector<string> vec = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    vector<string> letterCombinations(string digits) {
        vector<string> ans;
        backtracking(ans, "", 0, digits);
        return ans;
    }
    void backtracking(vector<string>& ans, string str, int index, string& digits){
        if(str.size() == digits.size()){
            if(str.size() != 0) ans.push_back(str);
            return;
        }
        int id = digits[index] - '0';
        for(int i = 0; i < vec[id].size(); i++){
            backtracking(ans, str + vec[id][i], index + 1, digits);
        }
    }
};

第一種方法:
這是discuss中看到的,分享的原因是代碼最後用了swap()函數,這樣的拷貝是不需要佔用內存的,特別好的想法

vector<string> letterCombinations(string digits) {
    vector<string> result;
    if(digits.empty()) return vector<string>();
    static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    result.push_back("");   // add a seed for the initial case
    for(int i = 0 ; i < digits.size(); ++i) {
        int num = digits[i]-'0';
        if(num < 0 || num > 9) break;
        const string& candidate = v[num];
        if(candidate.empty()) continue;
        vector<string> tmp;
        for(int j = 0 ; j < candidate.size() ; ++j) {
            for(int k = 0 ; k < result.size() ; ++k) {
                tmp.push_back(result[k] + candidate[j]);
            }
        }
        result.swap(tmp);
    }
    return result;
}

python
python當然很適合這道題目
先看下遞歸的寫法:

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        m = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
        ans = []
        if len(digits) == 0: return []
        if len(digits) == 1:
            return list(m[digits[0]])
        else:
            result = self.letterCombinations(digits[1:])
            for r in result:
                for j in m[digits[0]]:
                    ans.append(j + r)
        return ans

最後貼幾個discuss上簡潔的python寫法:
遞歸:

class Solution(object):
def letterCombinations(self, digits):
    dic = {'0':' ', '1':'*', '2':'abc', '3':'def', '4':'ghi','5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'} 
    return [a + b for a in dic.get(digits[:1], '') for b in self.letterCombinations(digits[1:]) or [''] ] or []

非遞歸:

class Solution(object):
def letterCombinations(self, digits):
    dic, res = {'0':' ', '1':'*', '2':'abc', '3':'def', '4':'ghi','5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'} , []
    for x in digits:
        res = [pre + c for c in dic[x] for pre in res or ['']]
    return res
class Solution:
    def letterCombinations(self, digits):
        if '' == digits: return []
        kvmaps = {'2': 'abc','3': 'def','4': 'ghi','5': 'jkl','6': 'mno','7': 'pqrs','8': 'tuv','9': 'wxyz'}
        return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])

這三個要特別注意的就是處理特殊情況:所以有or [ ] / or [”]的加入

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