题目:
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
解读:给与一组由0-9组成的整数串,每个整数代表26个字母中的若干个,参考手机上的标准。给出由这些整数代表的字母组成的字母串的合集。
思路:采用循环迭代的方式,第一个数字的字母与第二个数字的字母进行组合,得出的结果和第三个数字的字母进行组合,得出的结果和第四个数字的字母进行组合....
注意点:字符串为0的时候返回空vector。否则,进行vector初始化为{“”}。
代码
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> answer;
string letter[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(digits.length() == 0) return answer;
answer = {""};
for(int i = 0; i<digits.length(); i++){
vector<string> t;
string l = letter[digits[i]-48];
for(int j = 0; j < answer.size(); j++){
if(l == "") break;
else {
for(int k = 0; k < l.length(); k++){
t.push_back(answer[j] + l[k]);
}
}
}
answer = t;
}
return answer;
}
};