1 题目描述
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.
其实就是九键键盘
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
难度:Medium
2 题目样例
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
3 题意分析
求排列组合即可。
4 思路分析
迭代的话其实也就是递归展开版,所以直接写成递归算了。
代码如下
class Solution {
public:
vector<string> letterCombinations(string digits) {
int len = digits.size();
vector<string> ans;
vector<string> s = {"", // for 1-indexed "", "abc", "def",
"ghi" , "jkl", "nmo",
"pqrs", "tuv", "wxyz"};
function<void(string, int)> f;
f = [&f, &s, len, &digits, &ans](string bf, int i){
if(i==len){
if(bf.size()!=0)
ans.emplace_back(bf);
}
else
for(auto &c:s[digits[i]-'0'])
f(bf+c, i+1);
};
f(string(""), 0);
return ans;
}
};
整体时间复杂度 但是 ,同时空间复杂度也是 和 ,其中n是digits的长度,复杂度用递归树法很容易看出。
5 后记
果然lambda和std::function满天飞就是很爽,不过还是要多学习一个写法啊。