Leetcode:17. Letter Combinations of a Phone Number
来源:互联网 发布:c语言vc6.0软件下载 编辑:程序博客网 时间:2024/06/06 02:31
Description
解题思路
1.DFS
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> result; string save; if (digits.size() == 0) return vector<string>(); int convert[10] = {0, 3, 6, 9, 12, 15, 19, 22, 26}; dfs(result, save, digits, 0, digits.size(), convert); return result; } void dfs(vector<string> &str, string save, string dig, int now, int size, int *convert){ if(now == size){ str.push_back(save); return; } int tmp = dig[now] - '0' - 2;//change '2' to 0, '3' to 1... for(int i = convert[tmp]; i < convert[tmp+1]; i++){ save.push_back('a' + i);//ex: a,b,c | d,e,f dfs(str, save, dig, now + 1, size, convert); save.pop_back(); } }};
2.采用迭代方法求解,以123为例
class Solution {public: vector<string> letterCombinations(string digits) { if (digits.size() == 0) return vector<string>(); static const vector<string> v = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> result; result.push_back(""); for (int i = 0; i < digits.size(); i++) { int num = digits[i]-'0'; if (num > 9 || num < 0) break; string s = v[num]; vector<string> t; for (int j = 0; j < s.size(); j++) { for (int k = 0; k < result.size(); k++) { t.push_back(result[k]+s[j]); } } result.swap(t); } return result; }};
阅读全文
0 0
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- leetcode Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- leetcode: Letter Combinations of a Phone Number
- Ubuntu下学习git第一天--安装、创建仓库、添加文件
- Java Web目前主流的框架以及正在兴起的框架
- 算法与数据结构——算法题 114:类似跳表数据结构,查找元素的复杂度(腾讯2016笔试题) ? 待解决
- java字符串
- 【程序猿分享】添加百度自动推送工具代码来提高收录
- Leetcode:17. Letter Combinations of a Phone Number
- c++ 11 默认初始化
- [惊险小说]末日盘旋(ED2000.COM).pdf 英文原版 免费下载
- PHP的4排序算法与普通排序比较
- 5种服务器网络编程模型讲解
- 吴恩达 神经网络和深度学习 第一部分课程 第一章课后习题 Neural Network Basics
- Java Struts2 框架表单中文乱码的解决方案
- Codeforces Round #451 (Div. 2)
- Python学习笔记