电话号码的字母组合(循环代替递归)

题目:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/submissions/
参考:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/zhi-xing-yong-shi-0mschao-guo-100yong-hu-by-su-ren/

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        /*
        *循环代替递归,res存储用了前k个字符时对应的字母集合
        *
        */
        int len = digits.size();
        vector<string> ve = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        vector<string> res;
        if(!len) return res;//特判空串
        res.push_back("");
        for(int k = 0,x,sz;k < len;k++) {
            x = digits[k]-'2';
            sz = res.size();
            for(int i = 0;i < sz;i++) {
                string str=res[i];
                res[i] += ve[x][0];
                for(int j = 1;j < ve[x].size(); j++) {
                    res.push_back(str+ve[x][j]);
                }
            }
        }
        return res;
    }
};
发布了71 篇原创文章 · 获赞 1 · 访问量 2802

猜你喜欢

转载自blog.csdn.net/weixin_43918473/article/details/104309309