leetcode 17 -- Letter Combinations of a Phone Number
来源:互联网 发布:godaddy ssl nginx 编辑:程序博客网 时间:2024/06/05 10:53
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; }};
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
- 数据库字符编码集查看命令
- linux常用命令
- IOS中的线程操作(1)
- 高并发处理方案
- ionic使用记录----popup
- leetcode 17 -- Letter Combinations of a Phone Number
- [置顶] Android Device Chooser 找不到真机设备问题
- 图灵机器人API接入
- solrcloud伪集群安装配置
- LINUX之awk命令
- Writing Better T-SQL: Top-Down Design May Not be the Best Choice
- 存储过程学习
- 网络抓包神器-Charles使用指南
- 断言