C++實現LeetCode(17.電話號碼的字母組合)

[LeetCode] 17. Letter Combinations of a Phone Number 電話號碼的字母組合

Given a string containing digits from 2-9inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: “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中每個數字可以代表若幹個字母,然後給一串數字,求出所有可能的組合。這裡可以用遞歸 Recursion 來解,需要建立一個字典,用來保存每個數字所代表的字符串,然後還需要一個變量 level,記錄當前生成的字符串的字符個數,實現套路和上述那些題十分類似。在遞歸函數中首先判斷 level,如果跟 digits 中數字的個數相等瞭,將當前的組合加入結果 res 中,然後返回。我們通過 digits 中的數字到 dict 中取出字符串,然後遍歷這個取出的字符串,將每個字符都加到當前的組合後面,並調用遞歸函數即可,參見代碼如下:

解法一:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res;
        vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationsDFS(digits, dict, 0, "", res);
        return res;
    }
    void letterCombinationsDFS(string& digits, vector<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 + 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{""};
        vector<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;
    }
};

到此這篇關於C++實現LeetCode(17.電話號碼的字母組合)的文章就介紹到這瞭,更多相關C++實現電話號碼的字母組合內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: