17. Letter Combinations of a Phone Number Medium
来源:互联网 发布:搜客云优化 编辑:程序博客网 时间:2024/05/22 06:54
这道题题意是很简单,但是真要写的话,像我这样的小白还是觉得无从下手。想了很久,决定先用迭代的方式完成
string let[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ans;
void recursion(string digits, string letter)
{
if(digits.size() == 0){ans.push_back(letter); return ;}
for (int i = 0; i < let[digits[0] - '0'].size() ; ++i)
{
recursion(digits.substr(1), letter + let[digits[0] - '0'][i]);
}
}
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits == "")return ans;
string s = "";
ans.clear();
recursion(digits, s);
return ans;
}
};
那个ans.clear()其实是不需要的,但是在leetcode提交的时候总是会出错,必须先清零,不知道为什么。。。迭代写起来是比较简洁,但是执行效果差强人意,要花3ms,后来我又写出了循环的版本,理论上这样更快,但是我的写法比较挫,还是要3ms。。。。下面贴出0ms的完美版本~
class Solution {
public:
vector<string> letterCombinations(string digits) {
string key[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ans;
if(digits == "")return ans;
ans.push_back("");
for (int i = 0; i < digits.size(); ++i)
{
int index = digits[i] - '0';
vector<string> temp;
for(int j = 0; j < ans.size(); j++){
for(int k = 0; k < key[index].size(); k++){
temp.push_back(ans[j] + key[index][k]);
}
}
ans = temp;
}
return ans;
}
};
- Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)
- 【Medium】17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number -Medium
- 17. Letter Combinations of a Phone Number Medium
- <LeetCode><Medium>17Letter Combinations of a Phone Number
- Medium 17题 Letter Combinations of a Phone Number
- (算法分析Week10)Letter Combinations of a Phone Number[Medium]
- 17.Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- Maven入门1-下载安装
- Chapter01 Java开发入门——Eclipse开发工具
- CSS盒子模型
- hive优化
- EM算法--应用到三个模型: 高斯混合模型 ,混合朴素贝叶斯模型,因子分析模型
- 17. Letter Combinations of a Phone Number Medium
- Javascript学习之6种常用继承方式详解
- linux中在/dev/下手动创建设备节点
- 几种常用的排序算法源代码以及效率比较
- 航空公司VIP客户查询
- 快速上手使用的基础脚手架webpack2-react-tools
- RecycleView添加下滑到底部的监听
- pyspark notebook的使用
- 腾讯2017暑假实习生编程题----字符换位