17、Letter Combinations of a Phone Number
电话号码的字母组合
给定一个数字字符串,返回所有可能的字母组合,可以代表。
一个映射的数字字母(就像在电话里按钮)如下所示。
注意事项
以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。
样例
给定 "23"
返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
我的代码:
class Solution {//递归形式,时间复杂度(3^n),空间复杂度(n)
public:
vector<string> const T={"","","abc","def",
"ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty())return res;
dfs(res,"",0,digits);
return res;
}
void dfs(vector<string> &res,string s,int rank,string digits)
{
if(rank==digits.length())res.push_back(s);
else
for(auto c:T[digits[rank]-'0'])
dfs(res,s+c,rank+1,digits);
}
};
经典代码:
// LeetCode, Letter Combinations of a Phone Number
// 时间复杂度O(3^n),空间复杂度O(1)
class Solution {
public:
const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
"ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> letterCombinations (const string &digits) {
vector<string deep="9"> result(1, "");
for (auto d : digits) {
const size_t n = result.size();
const size_t m = keyboard[d - '0'].size();
result.resize(n * m);
for (size_t i = 0; i < m; ++i)
copy(result.begin(), result.begin() + n, result.begin() + n * i);
for (size_t i = 0; i < m; ++i) {
auto begin = result.begin();
for_each(begin + n * i, begin + n * (i+1), [&](string &s) {
s += keyboard[d - '0'][i];
});
}
}
return result;
}
};