[LeetCode]17. Letter Combinations of a Phone Number
来源:互联网 发布:淘宝有的不能极速退款 编辑:程序博客网 时间:2024/06/06 17:32
Description
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.
Example
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.
Discussion
这是一个典型的遍历搜索问题。我们可以采用深度优先搜索的方法。输入给出一串数字,每一个数字给搜索树加一层。
算法的时间复杂度为O(3^n)
。
C++ Code
class Solution {public: vector<string> letterCombinations(string digits) { string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector<string> answer; if(digits.length() == 0) { return answer; } dfs(digits, dict, 0, "", answer); return answer; } void dfs(string digits, string dict[], int level, string prefix, vector<string> &answer) { if(level == digits.length()) { answer.push_back(prefix); return; } int index = digits[level] - '2'; //在字典dict中的下标 //遍历该数字对应的每一种字符情况 for(int i = 0; i < dict[index].size(); i++) { dfs(digits, dict, level + 1, prefix + dict[index][i], answer); } }};
阅读全文
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
- Kaggle 入门:探索泰坦尼克号事故幸存情况分析
- 图像识别前处理---学习(1)
- Ubuntu下MySQL简单操作
- NOIP 2006普及组 明明的随机数详解
- java序列化与反序列化(4)------jdk原生序列化机制实现深拷贝
- [LeetCode]17. Letter Combinations of a Phone Number
- pymysql
- 好用的chrome插件
- SpringBoot任务调度案例(学习笔记)
- jQuery.extend()的实现方式详解及实例
- 装饰器
- 拉格朗日插值法学习小记
- 一对多 多对一 多对多
- io流使用static_cast转换输出字符串地址