leetcode 17 -- Letter Combinations of a Phone Number
2015-06-03 10:52
495 查看
Letter Combinations of a Phone Number
题目: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”].
题意:
输入类似一串数字,返回可能出现在手机按键上的字母。上面有例子。
思路:
这种不明确循环次数和范围的一般都是用回溯法(递归)来求解,用dfs(深度优先搜索)即可,和八皇后问题类似。
代码:
//列举出所有可能出现的字符串 string key_val[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; class Solution { public: //深度优先搜索,ret是返回结果,dep是字符串的层次(深度),cur_ret是当前的可能结果,digits是目标字符串 void dfs(vector<string> &ret, int dep, string &cur_ret, string digits){ //如果深度已经到达目标字符串末尾,就返回 if(dep == digits.size()){ ret.push_back(cur_ret); return; } //通过深度获取当前字符串 string cur_str = key_val[digits[dep]-'0']; //对每一个字符再进行dfs。 for(int i = 0; i < cur_str.size(); ++i){ cur_ret.push_back(cur_str[i]); dfs(ret, dep+1, cur_ret, digits); //这个保证返回时cur_ret还是为空。 cur_ret.pop_back(); } } vector<string> letterCombinations(string digits){ vector<string>ret; //注意判断0的情况 if(digits.size() == 0){ return ret; } string cur_re(""); dfs(ret, 0, cur_re, digits); return ret; } };
相关文章推荐
- MVC-EditorFor与TextBoxFor的区别
- 织梦dede自定义内容分页,datalist运用实例
- 对于Python装饰器使用的一些建议
- SAT阅读解题思路指导:理解与推理
- 11111
- 网络抓包神器-Charles使用指南
- 网易新闻iOS版使用的18个开源组件
- Apache Shiro 快速入门教程,shiro 基础教程
- 存储过程学习
- HDU-2018
- 在排好序的数组中添加一个数字,将添加后的数字插入到数组合适的位置
- Android 模块化编程之引用本地的 aar
- Writing Better T-SQL: Top-Down Design May Not be the Best Choice
- 图灵机器人API接入
- htmlunit官网简易教程(翻译)
- ios:KVC的概述与使用
- A*寻路算法与它的速度
- iOS8中使用CoreLocation定位
- IOS中的线程操作(1)
- libsvm参数说明