LeetCode刷题(C++)——Letter Combinations of a Phone Number(Medium)
来源:互联网 发布:五金冲压模具设计软件 编辑:程序博客网 时间:2024/06/15 02:59
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
思路:第一眼看到这道题觉得不难,只需要利用for循环暴力寻找所有的组合结果就可以了,但是仔细一想发现,我们事先不知道digits的大小,于是就无法确定使用for循环的层数。怎么办呢?嗯,可以用递归来代替for循环。那么递归我们要递归什么呢?当然是要递归digits中的数字啦,然后对每个数字对应的字符进行遍历,来组合所有的可能。
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> letter;if (digits.empty())return letter;vector<string> num = { "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz" };string let;dfs(digits, letter, let, 0, num);return letter;}void dfs(string& digits, vector<string>& letter, string& let, int pos, vector<string> num){if (pos == digits.size()){letter.push_back(let);return;}int x = (digits[pos] - '0') - 2;string s = num[x];for (int i = 0; i < s.size();i++){let.push_back(s[i]);dfs(digits, letter, let, pos + 1, num);let.pop_back();} }};
1 0
- LeetCode刷题(C++)——Letter Combinations of a Phone Number(Medium)
- 题解——Leetcode 17.Letter Combinations of a Phone Number 难度:Medium
- LeetCode-17- Letter Combinations of a Phone Number(查表/递归)-Medium
- <LeetCode><Medium>17Letter Combinations of a Phone Number
- Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)
- [LeetCode] 017. Letter Combinations of a Phone Number (Medium) (C++/Java/Python)
- LeetCode——Letter Combinations of a Phone Number
- leetcode 017 —— Letter Combinations of a Phone Number
- LeetCode题解——Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number —— Leetcode
- LeetCode——17. Letter Combinations of a Phone Number
- Leetcode——17. Letter Combinations of a Phone Number
- leetcode—Letter Combinations of a Phone Number
- LeetCode 题解(77): Letter Combinations of a Phone Number
- LeetCode (17)Letter Combinations of a Phone Number
- leetcode系列(37)Letter Combinations of a Phone Number
- (Java)LeetCode-17. Letter Combinations of a Phone Number
- LeetCode (17)Letter Combinations of a Phone Number
- hdoj 5879 Cure
- 美团推荐算法实践
- 文章标题
- Pascal学习之路1——变量常量定义
- Ubuntu下QT安装
- LeetCode刷题(C++)——Letter Combinations of a Phone Number(Medium)
- 0420- 兄弟选择器
- 计算机视觉(视频追踪检测分类、监控追踪)常用测试数据集
- Tensorflow分布式并行技术实践
- 统计语言模型
- MySQL管理
- PAP和CHAP协议介绍
- Android端的socket 编程
- 再谈final这个关键字