LeetCode 之 Letter Combinations of a Phone Number
来源:互联网 发布:淘宝卖家违规扣分 编辑:程序博客网 时间:2024/06/06 18:52
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.
这个题其实就是一个深度搜索,假如我输入345则有:
设一个深度值(其实就是按的电话号码的第i位),用一个nextResult代表下一层返回来的string的vector,对这个vector里的数据,用本层的字符串的每一个char都插在前面,然后假如result,返回。这里需要注意的是对下一层返回的字符串每一个都要使用多次,所以注意要用一个temp来每次都copy一次。
代码(12ms):
class Solution {public: string digitString [10]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; vector<string> letterCombinations(string digits) { vector <string>result; if(digits=="") result.push_back(""); else result = DFS(digits,0); return result; } vector<string> DFS(string digits , int depth){ vector<string>result; if(digits.size()==0) return result; //当前处理的char转为int int current = digits[depth]-'0'; if(depth == digits.size()-1){ for(int i =0 ;i<digitString[current].size();i++){ result.push_back(digitString[current].substr(i,1)); } return result; } //获取下一层的数据 vector<string>nextResult=DFS(digits,depth+1); for(int i=0 ;i < nextResult.size();i++){ for(int j =0 ;j < digitString[current].size();j++){ //对下一层的每一个string都加一个本层的char,放在vector里 string temp = nextResult[i]; temp.insert(0,digitString[current].substr(j,1)); result.push_back(temp); } } return result; }};
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
- 如何利用Excel数据有效性制作多级联动下拉列表
- MAC上搭建Windows Phone 8 开发环境——VMware Fusion下Win8 “无法安装Hyper-V, 某个虚拟机监控程序正在运行”问题解决的办法
- Mac OS下文件夹(带linux部分)
- 黑马程序员之7k面试题之银行业务调度系统
- setup time & hold time
- LeetCode 之 Letter Combinations of a Phone Number
- java模板代码
- C# 事件委托 【开门两次 开枪】
- MQTT的学习研究(九)基于HTTP GET MQTT 抓取消息服务端使用
- “corruption in the heap” vector内存释放错误
- UIAlertView笔记
- C++标准库类型(转)
- 算法导论第15章 最优二叉树
- javascript获取光标位置以及设置光标位置(兼容firefox)