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.
解:就是暴力!
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> letter = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
int len1 = digits.size();
vector<string> res;
if(len1 == 0) return vector<string>();
res.push_back("");
for(int i = 0; i < len1; ++i){
int num = digits[i] - '0';
if(num < 0 || num > 9) break;
vector<string> tmp;
for(int j = 0; j < letter[num].size(); ++j){
for(int k = 0; k < res.size(); ++k){
tmp.push_back(res[k] + letter[num][j]);
}
}
res.swap(tmp);
}
return res;
}
};
本文介绍了一个简单的算法问题——电话号码的字母组合。给定一个仅包含数字的字符串,返回所有可能的由这些数字对应的字母组成的组合。文章提供了一个C++实现的示例代码,展示了如何通过迭代方式生成所有可能的组合。
1128

被折叠的 条评论
为什么被折叠?



