目录
题目链接
Letter Combinations of a Phone Number - LeetCode
注意点
- 可以不用按字典序排序
解法
解法一:输入的数字逐个处理,在已经生成的字符串后面追加该当前数字对应的所有字符。时间复杂度为O(n)
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans,temp_ans;
map<char,vector<string>> mp;
mp['2']={"a","b","c"};
mp['3']={"d","e","f"};
mp['4']={"g","h","i"};
mp['5']={"j","k","l"};
mp['6']={"m","n","o"};
mp['7']={"p","q","r","s"};
mp['8']={"t","u","v"};
mp['9']={"w","x","y","z"};
int i,j,k,n = digits.length();
for(i = 0;i < n;i++)
{
int size = ans.size();
vector<string> v = mp[digits[i]];
for(j = 0;j < v.size();j++)
{
for(k = 0;k < size;k++)
{
string temp=ans[k]+v[j];
temp_ans.push_back(temp);
}
if(size==0) temp_ans.push_back(v[j]);
}
swap(ans,temp_ans);
temp_ans.clear();
}
return ans;
}
};
小结
- 代码网上看来的,自己重新打了一遍。相比其他博客,这个算是最好理解的。