[leetcode_17]Letter Combinations of a Phone Number

输入数字串,输出对应手机键盘上所有的字母串的情况。

 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
40
41
class Solution {
public:
    vector<string> ans;
    vector<string> letterCombinations(string digits) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<string> map = GenMap();
        ans.clear();
        string item = "";
        letterCStep(digits, 0, item, map);
        return ans;
    }
private:
    void letterCStep(string digits, int step, string item, vector<string>& map) {
        if (step >= digits.length()) {
            ans.push_back(item);
            return;
        } else {
            int index = digits[step] - '0';
            for (int i = 0; i < map[index].size(); i++) {
                item.push_back(map[index][i]);
                letterCStep(digits, step + 1, item, map);
                item.erase(item.end() - 1);
            }
        }
    }
    vector<string> GenMap() {
        vector<string> map;
        map.clear();
        map.push_back(" ");
        map.push_back("");
        map.push_back("abc");
        map.push_back("def");
        map.push_back("ghi");
        map.push_back("jkl");
        map.push_back("mno");
        map.push_back("pqrs");
        map.push_back("tuv");
        map.push_back("wxyz");
        return map;
    }
};
Licensed under CC BY-NC-SA 4.0