Facebook Phone Interview: Phone Number to Letter Combinations (easy)
2016-03-23 07:41
288 查看
Input: string of digits of arbitrary length
output: print all possible letter combinations for those digits to screen.
output: print all possible letter combinations for those digits to screen.
// This is a typical DFS algorithm. // Suppose we dont know the phone screen layout. we need to set a dictionary first. // map<char, vector<char> > dict; // we use a map structure to map digits to letters. vector<string> ret; void createDict() { dict.clear(); dict['2'].push_back('a'); dict['2'].push_back('b'); dict['2'].push_back('c'); dict['3'].push_back('d'); dict['3'].push_back('e'); dict['3'].push_back('f'); dict['4'].push_back('g'); dict['4'].push_back('h'); dict['4'].push_back('i'); dict['5'].push_back('j'); dict['5'].push_back('k'); dict['5'].push_back('l'); dict['6'].push_back('m'); dict['6'].push_back('n'); dict['6'].push_back('o'); dict['7'].push_back('p'); dict['7'].push_back('q'); dict['7'].push_back('r'); dict['7'].push_back('s'); dict['8'].push_back('t'); dict['8'].push_back('u'); dict['8'].push_back('v'); dict['9'].push_back('w'); dict['9'].push_back('x'); dict['9'].push_back('y'); dict['9'].push_back('z'); } // dfs algorithm. void dfs(int dep, int maxDep, string& s, string ans) { if(dep == maxDep) { ret.push_back(ans); return; } for(int i = 0; i < dict[s[dep]].size(); ++i) { dfs(dep + 1, maxDep, s, ans+ dict[s[dep]][i]); } } vector<string> letterCombinations(string digits) { ret.clear(); createDict(); dfs(0, digits.size(), digits, ""); return ret; }
相关文章推荐
- 通过xib创建viewcontroller
- 通过storyboard创建控制器
- ios启动过程
- 1692: [Usaco2007 Dec]队列变换|后缀数组|贪心
- 自定义控件之TabIndicator
- [bzoj2440][中山市选2011]完全平方数
- laravel Eloquent操作
- 用数学方法解决工程问题系列(三) 判断任意给定一点是否在多边形内
- laravel 控制器类DB类操作
- 数独求解 DFS && DLX
- Java命名规范及给自己写的方法添加注解
- 【BZOJ 4448】 [Scoi2015]情报传递|树链剖分|树套树
- 【杭电oj】2277 - Change the ball(找规律)
- 【BZOJ 4443】 [Scoi2015]小凸玩矩阵|二分|最大匹配|匈牙利
- Using multiple LLVM versions on Ubuntu
- Uncovering the new RPC Client Access Service in Exchange 2010 (Part 3)
- Spring源码之bean的加载(五)准备创建bean
- 并查集
- Spring源码之bean的加载(四)获取单例
- 解决DRM找不到的问题。