Letter Combinations of a Phone Number [leetcode]谈谈循环解法的两种思路
来源:互联网 发布:网络情歌对唱 编辑:程序博客网 时间:2024/06/05 06:02
本系列博文中有很多两种思路的,其实是因为第一遍刷题的时候有一个想法,第二遍刷题的时候已经忘掉之前的思路了,又有新的想法了。
同时大部分代码我也同时PO到leetcode的对应题目的问答中去了,所以如果你也查看问题讨论的话会发现有和我一模一样的代码,其实就是我PO的:)
书接正文,基于循环的两种思路如下:
第一种思路
比如“234”这个字符串,我可以先将0...1的所有排列找到-->{"a", "b", "c"}
再进一步将0...2的所有排列找到-->{"ad", "ae","af", "bd", "be", "bf", "cd", "ce", "cf"}
如此循环...直到字符串末尾。实现如下
vector<string> letterCombinations(string digits) { vector<string> res; string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; res.push_back(""); for (int i = 0; i < digits.size(); i++) { vector<string> tempres; string chars = charmap[digits[i] - '0']; for (int c = 0; c < chars.size();c++) for (int j = 0; j < res.size();j++) tempres.push_back(res[j]+chars[c]); res = tempres; } return res; }
先生成"234"的第一个可行解"adg",再在可行解上衍生出其他解
类似数数的时候遇到9就变成0并进位
vector<string> letterCombinations(string digits) {string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};vector<string> res;string alpha;for (int i = 0; i < digits.size(); i++)alpha += charmap[digits[i] - '0'][0];while (true){res.push_back(alpha);//寻找可行解bool find = false;for (int i = digits.size() - 1; i >= -1 && ! find; i--){if (i == -1)return res;//遍历结束string chars = charmap[digits[i] - '0'];if (alpha[i] == chars[chars.size() - 1])//遍历第i个数字的最后一个可行解,重置并寻找第i+1个数字的可行解{alpha[i] = chars[0];continue;}for (int c = 0; c < chars.size() && ! find; c++)//遍历第i个数字的其他可行解{ if (alpha[i] == chars[c]) { alpha[i] = chars[c+1]; find = true; }}}}}
2 0
- Letter Combinations of a Phone Number [leetcode]谈谈循环解法的两种思路
- LeetCode 17. 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
- 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
- android学习笔记1
- OpenCV改变图像大小的操作
- 软件采购必备:软件供应商评估表 之一(共七)
- 安装redis
- 获取远程进程的命令行参数(xp、win7测试通过)
- Letter Combinations of a Phone Number [leetcode]谈谈循环解法的两种思路
- struts 下载文件
- autocomplete的参数的几个用法说明
- hdu 2896 (病毒侵袭)
- InputFormat&OutputFormat
- java学习笔记
- 格式化银行卡号
- Android判断apk是否存在
- Eclipse使用hibernate插件