题目:
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"};
};