17. Letter Combinations of a Phone Number (Medium)

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.

Solution 1: DFS

这道题让我们求电话号码的字母组合,即数字2到9中每个数字可以代表若干个字母,然后给一串数字,求出所有可能的组合,相类似的题目有 Path Sum II 二叉树路径之和之二,Subsets II 子集合之二,Permutations 全排列,Permutations II 全排列之二,Combinations 组合项, Combination Sum 组合之和和 Combination Sum II 组合之和之二等等。我们用递归Recursion来解,我们需要建立一个字典,用来保存每个数字所代表的字符串,然后我们还需要一个变量level,记录当前生成的字符串的字符个数,实现套路和上述那些题十分类似,代码如下:

class Solution {
    vector<string> dict = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if (digits.empty()) return res;
        DFS(digits, 0, "", res);
        return res;
    }

    void DFS(string digits, int level, string out, vector<string>& res) {
        if (level == digits.size()) res.push_back(out);
        else {
            string str = dict[digits[level]-'2'];
            for (int i = 0; i < str.size(); ++i) {
                out += str[i];
                DFS(digits, level+1, out, res);
                out.pop_back();
            }
        }
    }
};

Solution 2: Iterative, BFS

vector<string> letterCombinations(string digits) {
    vector<string> res;
    if (digits.empty()) return res;
    vector<string> dict = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    res.push_back("");

    for (int i = 0; i < digits.size(); ++i) {
        int n = res.size();
        string str = dict[digits[i]-'2'];
        for (int j = 0; j < n; ++j) {
            string tmp = res.front();
            res.erase(res.begin());
            for (int k = 0; k < str.size(); ++k) {
                res.push_back(tmp+str[k]);
            }
        }
    }

    return res;
}

results matching ""

    No results matching ""