leetcode 17.电话号码的字母组合

题目

解法 BFS + hash

/*
广度遍历,利用队列实现
*/
class Solution {
private:
    unordered_map<char,string> tel_map;
    queue <string> re_queue;
    vector<string> result;
public:
    Solution()
    {
        tel_map = {{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}};
    }
    vector<string> letterCombinations(string digits) {
        
        if(digits.length() ==  0)
            return result;

        auto p = tel_map.find(digits[0]);
        string tmp1 = p->second;
        for(int i = 0 ; i < tmp1.length();i++)
        {
            string tmp2;
            tmp2.push_back(tmp1[i]);
            re_queue.push(tmp2);
        }
        
        for(int i = 1 ; i < digits.length();i++)
        {

            unordered_map<char,string>::iterator p = tel_map.find(digits[i]);
            string tmp3 = p->second;
            vector <string> tmp4;
            while(!re_queue.empty())
            {
                string tmp5 = re_queue.front();
                re_queue.pop();
                for(int j = 0 ; j < tmp3.length();j++)
                {
                    string tmp6 = tmp5 + tmp3[j];
                    tmp4.push_back(tmp6);
                }
            }

            for(int k = 0; k < tmp4.size();k++)
            {
                re_queue.push(tmp4[k]);
            }
        }

        while(!re_queue.empty())
        {
            result.push_back(re_queue.front());
            re_queue.pop();
        }
        return result;
    }
};

时间复杂度为 O ( 3 N ∗ 4 M ) O(3^N * 4^M) O(3N4M) N + M为输入数字的总数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值