1. 程式人生 > >[LeetCode] Letter Combinations of a Phone Number 電話號碼的字母組合

[LeetCode] 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.

這道題讓我們求電話號碼的字母組合,即數字2到9中每個數字可以代表若干個字母,然後給一串數字,求出所有可能的組合,相類似的題目有Path Sum IISubsets IIPermutationsPermutations IICombinationsCombination Sum 和Combination Sum II 等等。我們用遞迴Recursion來解,我們需要建立一個字典,用來儲存每個數字所代表的字串,然後我們還需要一個變數level,記錄當前生成的字串的字元個數,實現套路和上述那些題十分類似。在遞迴函式中我們首先判斷level,如果跟digits中數字的個數相等了,我們將當前的組合加入結果res中,然後返回。否則我們通過digits中的數字到dict中取出字串,然後遍歷這個取出的字串,將每個字元都加到當前的組合後面,並呼叫遞迴函式即可,參見程式碼如下:

解法一:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res;
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationsDFS(digits, dict, 
0, "", res); return res; } void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) { if (level == digits.size()) {res.push_back(out); return;} string str = dict[digits[level] - '0']; for (int i = 0; i < str.size(); ++i) { letterCombinationsDFS(digits, dict, level + 1, out + string(1, str[i]), res); } } };

這道題我們也可以用迭代Iterative來解,在遍歷digits中所有的數字時,我們先建立一個臨時的字串陣列t,然後跟上面解法的操作一樣,通過數字到dict中取出字串str,然後遍歷取出字串中的所有字元,再遍歷當前結果res中的每一個字串,將字元加到後面,並加入到臨時字串陣列t中。取出的字串str遍歷完成後,將臨時字串陣列賦值給結果res,具體實現參見程式碼如下:

解法二:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res{""};
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for (int i = 0; i < digits.size(); ++i) {
            vector<string> t;
            string str = dict[digits[i] - '0'];
            for (int j = 0; j < str.size(); ++j) {
                for (string s : res) t.push_back(s + str[j]);
            }
            res = t;
        }
        return res;
    }
};

類似題目:

參考資料: