17.Letter Combinations of a Phone Number¶
Tags: Medium
String
Backtracking
Links: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Given a string containing digits from 2-9
inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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.
class Solution {
map<char, string> m = {{'2',"abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"},{'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty()) return res;
if (digits.size() == 1) {
string tmp = m[digits[0]];
for (auto e : tmp) {
string str;
str.push_back(e);
res.push_back(str);
}
}
else {
vector<string> store = letterCombinations(digits.substr(1));
string tmp = m[digits[0]];
for (int i = 0; i < tmp.size(); ++i) {
string str; str.push_back(tmp[i]);
for (int j = 0; j < store.size(); ++j) {
res.push_back(str + store[j]);
}
}
}
return res;
}
};
这道题目其实考察的就是简单的回溯法,然而很神奇的是它的时间判定:
Runtime: 8 ms, faster than 5.54% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 8.6 MB, less than 82.86% of C++ online submissions for Letter Combinations of a Phone Number.
当然也可以把字典换成vector
,效率并没有太多的提升。另外需要注意输入字符串为空的情况。