Type:medium
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
本题题意为给定一串数字,按照9宫格对应关系,输出所有可能代表的字符串。
首先建立v字符数组,建立每个数字与对应的所有字符的关系。建立返回的ret这个vector,赋一个空的初值,否则接下来的程序处理会报错。
挨个读取digits字符串的数字,定位这个数字所代表的字符串,将原ret容器中所有字符串加上这个数字所代表的的所有字符即可。
如代码中所示,temp这个vector进行了时间复杂度上为n^2次操作,负责将原ret容器的每个字符串首先加上vv这个字符串中第一个字符,再将ret原字符串加上vv第二个字符,直至加到数字num对应的容器v中的字符串(vv)最后一位。最后将这个temp赋给ret。
class Solution {
public:
vector<string> letterCombinations(string digits) {
int n = digits.length();
if(n == 0) return vector<string>();
vector<string> ret;
vector<string> v = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
ret.push_back(""); //initialize
vector<string> temp;
for(int i=0; i<n; i++){
int num = digits[i] - '0';
string vv = v[num];
int len = vv.length();
for(int j=0; j<ret.size(); j++){
for(int m=0; m<len; m++){
temp.push_back(ret[j] + vv[m]);
}
}
ret.swap(temp);
temp.clear();
}
//ret.erase(ret.begin());
return ret;
}
};