[Leetcode] 17. Letter Combinations of a Phone Number 解题报告
来源:互联网 发布:手机淘宝官网首页 编辑:程序博客网 时间:2024/04/30 05:54
题目:
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)将hash表定义为数组而不是vector;2)将DFS中的参数digits定义为const string& 类型,不仅可以提高安全性,而且可以提高运行效率(避免了递归过程中字符串的多次复制)。
代码:
class Solution { public: vector<string> letterCombinations(string digits) { if(digits.size() ==0) return {}; DFS(digits, 0, ""); return result; } private: void DFS(const string& digits, int k, string tem) { if(k >= digits.size()) result.push_back(tem); if(!(digits[k]>'1' && digits[k]<= '9')) // invalid number detected return; for(auto val: hash[digits[k]-'0']) // add each character to current tem DFS(digits, k + 1, tem + val); } vector<string> result; string hash[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; };
0 0
- [leetcode] 17. Letter Combinations of a Phone Number 解题报告
- [Leetcode] 17. Letter Combinations of a Phone Number 解题报告
- leetcode解题报告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 解题报告
- Letter Combinations of a Phone Number --leetcode解题报告
- [leetCode 解题报告]017. Letter Combinations of a Phone Number
- [leetCode 解题报告]080. Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number解题报告
- [leetcode javascript解题]Letter Combinations of a Phone Number
- leetcode解题方案--017--Letter Combinations of a Phone Number
- leecode 解题总结: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
- Java学习记录01
- 109. Convert Sorted List to Binary Search Tree
- [Leetcode] 16. 3Sum Closest 解题报告
- jdbc
- 浅谈activity生命周期
- [Leetcode] 17. Letter Combinations of a Phone Number 解题报告
- jdbc
- 9.Linux驱动开发前奏(1)-驱动开发概述
- 解决ntp的错误 no server suitable for synchronization found
- Android API Guide for Animation and Graphics(四)—— 动画与图形(帧动画)
- 如何在不重启电脑的情况下修改主机名
- windows内核情景分析--窗口消息
- Agent不能同步master的解决方法
- Hadoop源码之----hadoop-common-project(一、工程目录结构)