LeetCode Algorithms 17. Letter Combinations of a Phone Number

题目难度: Medium


原题描述:

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].


题目大意:

        输入一串数字,让你根据上面的电话按键图片中每个数字对应的字母集合,构造一个按照数字顺序的所有可能组合的字符串集合(笛卡尔积的方式)。


解题思路:

        首先要注意的是,数字0和1对应的字母集合都是空的,唉,题目都没说清楚。。。解题思路是很明确的,初始每个数字对应一个字符串vector,里面的内容为每个字符一个字符串,然后根据输入数字的顺序对字符串vector两两做笛卡尔积连接起来,不断拼接起来,最后的一个字符串vector就是结果了。


时间复杂度分析:

        假设每个数字一开始对应的字符串数量为n,输入数字串的长度为m,则时间复杂度为O(n^m)。


以下是代码:

vector<string> v[10];
string s[10] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

void init()
{
    for(int i=0 ; i<10 ; ++i){
        for(int j=0 ; j<s[i].size() ; ++j){
            string temp;
            temp.append(1,s[i][j]);
            v[i].push_back(temp);
        }
    }
}

vector<string> letterCombinations(string digits)
{
    vector<string> temp[1000];
    if(digits.size()==0)
        return temp[0];
        
    temp[0].push_back("");
    for(int i=0 ; i<digits.size() ; ++i){
        int sIndex = digits[i]-'0';
        for(int x = 0 ; x<temp[i].size() ; ++x){
            for(int y=0 ; y<s[sIndex].size(); ++y){
                temp[i+1].push_back(temp[i][x] + s[sIndex][y]);
            }
        }
    }
    return temp[digits.size()];
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值