leetcode 17. Letter Combinations of a Phone Number

题意

给定一个数字字符串,枚举各个数字对应的字母组合后的字符串(不重复)。

题解

一个串中字母的重复次数,即后面字母形成串的可能种数。
给定数字”234”,对应串“abc”、“def”、“ghi”,所有可能的串的种数是3 * 3 * 3 = 27;
第一个串的每个字母的重复次数为:len(“def”) * len(“ghi”) = 9,第二、第三个串以此类推。

代码


class Solution {
public:
    vector<string> letterCombinations(string digits) {
        // map<char, string> dict;{('2',"abc"), ('3',"def"), ('4', "ghi"), ('5', "jkl"), ('6', "mno"),
        //                          ('7', "pqrs"), ('8', "tuv"), ('9', "wxyz") };
        const int MAXSIZE = 10;
        string dict[MAXSIZE] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        if (digits.length() == 0)
        {
            vector<string> temp;
            return temp;
        }
        int len = digits.length();
        int result_size = 1; 
        vector<string> strs;
        vector<int> strs_len;


        for (int i = 0; i < len; i++)
        {
            string temp = dict[digits[i] - '0'];
            strs.push_back(temp);
            strs_len.push_back(temp.length());
            result_size *= temp.length(); //calu the all conditions

        }

        int repeated_size = result_size;
        vector<string> result(result_size);

        for (int i = 0; i < len; i++)
        {
            repeated_size = repeated_size / strs_len[i]; //当前串中各个字母的重复次数,即后面字母形成一个串的可能种数
            int index = 0;
            while (index < result_size)
            {
                for (int j = 0; j < strs_len[i]; j++)
                {
                    for (int k = 0; k < repeated_size; k++)
                    {
                        string temp = result[index] + strs[i][j];

                        result[index++] += strs[i][j];
                    }

                }
            }

        }
        vector<string> unique_res;
        set<string> temp;
        for (int i = 0; i < result.size(); i++)
        {
            if (!temp.count(result[i]))
            {
                unique_res.push_back(result[i]);
                temp.insert(result[i]);
            }
        }
        //return result;
        return unique_res;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值