題目難度: 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()];
}