17-Letter Combinations of a Phone Number
来源:互联网 发布:mysql front 编辑:程序博客网 时间:2024/06/06 07:05
题目
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”].
分析
这个也是用到DFS,这是自己写的比较快的一个程序,因为之前被虐的够惨,像Permutation 系列,N-Queens 系列都是这个套路。
递归解决问题,不过我写的函数总是参数特别多。
值得一提的是,在这个函数里第一次用到string 的push_back() 和 pop_back()函数,原本以为只有vector 才有,是我孤陋寡闻了·······
实现
class Solution {
public:
vector letterCombinations(string digits) {
//存放结果序列 vector<string> result; if (digits.length() == 0) return result;//索引 string dict[] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//中间结果,也就是一个string string subResult=""; letterCombinationsDFS(result,dict,digits,subResult,0); return result;}void letterCombinationsDFS(vector<string>& result,string *dict,string& digits,string& subResult,int num){ if (num == digits.length()) { result.push_back(subResult); return; } else { string tmp = dict[digits[num] - '2']; for (int i = 0; i < tmp.length(); i++) { //向string 的end 添加一个字符 subResult.push_back(tmp[i]); letterCombinationsDFS(result, dict, digits, subResult, num + 1); //从string的末端删除一个字符 subResult.pop_back(); } }}
};
阅读全文
0 0
- 17,Letter Combinations of a Phone Number
- #17 Letter Combinations of a Phone Number
- 17Letter Combinations of a Phone Number
- 17 Letter Combinations of a Phone Number
- 17 Letter Combinations of a Phone Number
- 【17】Letter Combinations of a Phone Number
- 17 Letter Combinations of a Phone Number
- 17-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
- 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
- Android开发,Kotlin的了解与学习(五)-----基本语法之集合相关
- JUNIT4.11源码阅读(一)--org.junit.Assert类
- JAVA的几种对象
- JS基础进阶1 数据类型
- Jedis示例
- 17-Letter Combinations of a Phone Number
- 阿里百川即时通讯的介绍
- Web 前端知识体系精简
- 一个完整webview的写法
- 31-NextPermutation
- HDU --- 4549 M斐波那契数列 【费马小定理+矩阵快速幂】
- 使用 libev 构建 TCP 响应服务器(echo server)的简单流程
- CodeForces
- c++2017-6-22语句