Letter Combinations of a Phone Number
来源:互联网 发布:mac上的视频编辑软件 编辑:程序博客网 时间:2024/06/07 05:49
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"].Note:Although the above answer is in lexicographical order, your answer could be in any order you want.
(1)先说一下遍历的方法。从第一个数字开始,将所有的字母添加到result中,然后,去掉第一个字符串,与下一个数字代表的字母依次组合,并添加到result中,直到完成所有字母的添加。代码如下:
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> dv(10); //0~9 dv[2] = "abc"; dv[3] = "def"; dv[4] = "ghi"; dv[5] = "jkl"; dv[6] = "mno"; dv[7] = "pqrs"; dv[8] = "tuv"; dv[9] = "wxyz"; vector<string> result; if(digits=="") //数组为空,直接返回 return result; result.push_back(""); //为首次循环添加一个空字符 for(int i=0;i<digits.size();i++){ int s=result.size(); //不能直接用size()函数,因为result的大小是变化的 for(int j=0;j<s;j++){ string t=result[0]; result.erase(result.begin()); //删除首字母 for(int k=0;k<dv[digits[i]-'0'].size();k++){ result.push_back(t+dv[digits[i]-'0'][k]); } } } }};
(2)采用深度优先搜索的办法(DFS),以递归的方式进行遍历。
class Solution {public: void dfs(string digits, int depth, string path, vector<string> dv, vector<string> &result) { if(depth == digits.size()) { result.push_back(path); return; } for(auto c: dv[digits[depth] - '0']) { dfs(digits, depth+1, path+c, dv, result); } } vector<string> letterCombinations(string digits) { vector<string> dv(10); //0~9 dv[2] = "abc"; dv[3] = "def"; dv[4] = "ghi"; dv[5] = "jkl"; dv[6] = "mno"; dv[7] = "pqrs"; dv[8] = "tuv"; dv[9] = "wxyz"; vector<string> result; if(digits.size() == 0) return result; dfs(digits, 0, "", dv, result); 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
- LeetCode18:Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- Android多屏幕适配方案
- Verilog学习笔记
- XCode升级后插件失效的原理与修复办法
- 打脸苹果,三星新品电视“国行”售价低于“美版”
- Unity中HideInInspector和SerializeField
- Letter Combinations of a Phone Number
- 【springmvc+mybatis项目实战】杰信商贸-22.合同货物附件生产厂家mapper关联
- Android--颜色,动画效果xml所在目录
- TableView 去掉多余行数、IOS最后一行Cell系统分割线顶头
- Inventor之入门
- oracle表关联方式错误导致不出结果
- jquery.validate使用攻略
- Redis单机多实体安装与主从配置
- oracle知识点杂记(持续更新)