LeetCode 17 电话号码的字母组合

dfs
定义string数组初始化后加;
char型 - ‘0’转为int型

class Solution {
public:
    vector<string> res;
    string path;
    const string map[10] = {
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
    };
    void dfs (string digits, int u) {
        if (path.size() == digits.size()) {
            res.push_back(path);
            return;
        }

        string letter = map[digits[u] - '0'];
        for (int i = 0; i < letter.size(); i ++) {
            path.push_back(letter[i]);
            dfs(digits, u + 1);
            path.pop_back();
        }
    }
    vector<string> letterCombinations(string digits) {
        res.clear();
        if (digits.size() == 0) return res;
        dfs(digits, 0);

        return res;
    }
};
posted @ 2022-09-02 16:37  hjy94wo  阅读(24)  评论(0)    收藏  举报