您的位置:首页 > 编程语言 > Go语言

LeetCode Algorithms 17. Letter Combinations of a Phone Number

2017-03-29 14:49 369 查看
题目难度: 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()];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string vector