17 Letter Combinations of a Phone Number
题目: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.
Letter Combinations of a Phone Number
解题思路:很显然这道题我们应该用暴力搜索来求解. 如果digits的长度是固定的(n), 则我们可以直接写一个n重for循环来解决. 但是现在的问题是digits的长度不是固定的, 因此我们也就不能直接用for循环来解决, 因为无法确定for循环的重数. 此时, 我们很容易想到回溯法, 因为回溯法实际上就是一个类似枚举的搜索尝试过程.
首先根据数字与字母的映射关系, 我们建立映射表来保存这种映射关系. 然后递归的搜索满足条件(index==digits.size()
)的结果. 代码如下所示.
class Solution {
public:
vector letterCombinations(string digits) {
vector ret;
if(digits.empty())
return ret;
vector table = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
string comb(digits.size(), 0);
helper(0, table, comb, digits, ret);
return ret;
}
void helper(int index, vector& table, string& comb, string& digits, vector& ret) {
if(index == digits.size()) {
ret.push_back(comb);
}
string letters = table[digits[index]-'0'];
for(int i = 0; i < letters.size(); ++i) {
comb[index] = letters[i];
helper(index+1, table, comb, digits, ret);
}
}
};