Leetcode—17.电话号码的字母组合【中等】

2023每日刷题(九)

Leetcode—17.电话号码的字母组合

Leetcode—17.电话号码的字母组合【中等】_第1张图片

回溯法解题

实现代码

class Solution {
public:
    vector<string> table = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","xyzw"};
    vector<string> letterCombinations(string digits) {
        int n = digits.size();
        if(n == 0) {
            return {};
        }
        vector<string> ans;
        string path(n, 0);
        function<void(int)> dfs = [&](int i) {
            if(i == n) {
                ans.emplace_back(path);
                return;
            }
            int num = digits[i] - '0';
            int k;
            for(auto &k : table[num]) {
                path[i] = k;
                dfs(i + 1);
            }        
        };
        dfs(0);
        return ans;
    }
};

测试结果

Leetcode—17.电话号码的字母组合【中等】_第2张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,算法,职场和发展,c++,回溯,lambda函数)