17. 电话号码的字母组合

题目

17. 电话号码的字母组合 官方题解

方法一:回溯算法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        unordered_map<char, string> phoneMap{
            {'2', "abc"},
            {'3', "def"},
            {'4', "ghi"},
            {'5', "jkl"},
            {'6', "mno"},
            {'7', "pqrs"},
            {'8', "tuv"},
            {'9', "wxyz"}
        };

        vector<string> combinations;
        if (digits.empty()) {
            return combinations;
        }

        string combination;
        dfs(combinations, phoneMap, digits, 0, combination);
        return combinations;
    }

    void dfs(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) {
        if (index == digits.size()) {
            combinations.push_back(combination);
        } else {
            char digit = digits[index];
            const string& letters = phoneMap.at(digit);
            for (const char& letter : letters) {
                combination.push_back(letter);
                dfs(combinations, phoneMap, digits, index + 1, combination);
                combination.pop_back();
            }
        }
    }
};