leetcode Letter Combinations of a Phone Number
来源:互联网 发布:ip是设备还是网络连接 编辑:程序博客网 时间:2024/06/08 08:01
此题是非常经典的递归回溯法,
递归代码
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> res; string temp(digits.size(), ' '); letterCombinationsHelper(digits, 0, temp, res); return res; } void letterCombinationsHelper(string &digits, int index, string &temp, vector<string> &res) { string nummap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; if(index==digits.size()) { res.push_back(temp); return ; } for(int i = 0; i < nummap[digits[index]-'0'].size(); ++i) { temp[index] = nummap[digits[index]-'0'][i]; letterCombinationsHelper(digits, index+1, temp, res); } }};
非递归运算
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> res; string nummap[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; vector<int> indexNum(digits.size(), 0); while(true) { string temp(digits.size(), ' '); for(int i = 0; i < digits.size(); ++i) temp[i] = nummap[digits[i]-'0'][indexNum[i]]; res.push_back(temp); int k = digits.size()-1; while(k>=0) { if(indexNum[k] < nummap[digits[k]-'0'].size()-1) { indexNum[k]++; break; } else { indexNum[k] = 0; k--; } } if(k<0) break; } return res; } };
参考http://www.cnblogs.com/TenosDoIt/p/3771254.html
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
- Shell Sort with array[]
- C++,string实现
- android4.4中jni的native的方法无法找到的解决方案
- Cytoscape绘图初探
- openstack学习笔记一 虚拟机启动过程代码跟踪
- leetcode Letter Combinations of a Phone Number
- 自己写EnumHelper
- 为jsp配置对外访问路径
- Java Thread 总结
- linux单用户模式
- [UIApplication sharedApplication].delegate 调用全局变量
- Android有效的处理Bitmap,减少内存
- L1 L2 LASSO问题
- 可变参数的深入探索