leetcode 17. Letter Combinations of a Phone Number
来源:互联网 发布:淘宝皇冠店可靠吗 编辑:程序博客网 时间:2024/06/03 07:32
相关问题
17. Letter Combinations of a Phone Number
77. Combinations
Discription
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.
Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路
递归/深度优先搜索。
具体实现包括递归和非递归两种形式。
时间复杂度:
空间复杂度:
代码
递归
class Solution {public: void dfs(vector<string> &res, string str, int i, string &digits, vector<string> &map) { // 边界条件 cout << digits.size(); if (i == digits.size()) { res.push_back(str); return; } // 递归 for (int j = 0; j < map[digits[i] - '0'].size(); j++) dfs(res, str + map[digits[i] - '0'][j], i + 1, digits, map); } vector<string> letterCombinations(string digits) { vector<string> map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> res; string str = ""; if (digits.size() == 0) return res; dfs(res, str, 0, digits, map); return res; }};
非递归
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> res; if (digits.size() == 0) return res; vector<string> map = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; queue<string> que; que.push(""); for (int i = 0; i < digits.size(); i++) // digits中的第i个字符,如"234" 中的 "2" { int n = que.size(); for (int j = 0; j < n; j++) // 队列中的第j个字符串 "abca" { string str = map[digits[i] - '0']; for (int k = 0; k < str.size(); k++) // digits中的第i个字符映射的字符串中第k个字符 "abc"的 "b" que.push(que.front() + str[k]); que.pop(); } } while(!que.empty()) { res.push_back(que.front()); que.pop(); } return res; }};
阅读全文
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
- <设计模式可复用面向对象软件的基础> [3.1]、职责链(C#)
- 渗透测试工具sqlmap基础教程
- 解决linux中IEDA报找不到JAVA_HOME问题
- (一、)maven下载、安装和配置 for windows
- Servlet
- leetcode 17. Letter Combinations of a Phone Number
- C#JavaScript交互
- Windows Socket五种I/O模型——代码全攻略
- jedis的使用
- 矿体剖面解译线按段高插入点
- Hive的安装教程(元数据放在本地Mysql)
- 如何删除数组中的元素
- UDDI
- 使用AMQP实现消息功能---RabbitMQ