Letter Combinations of a Phone Number 题解
题目来源:https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
Description
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.
Example
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.
Solution
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty())
return vector<string>();
vector<string> alphaMap = {
" ",
" ", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"
};
auto n = digits.size();
vector<vector<string> > dp(n + 1);
dp[0] = vector<string>{""};
int i;
for (i = 0; i < n; i++) {
const string& alphas = alphaMap[digits[i] - '0'];
for (auto c : alphas) {
for (auto str : dp[i]) {
dp[i + 1].push_back(str + c);
}
}
}
return dp.back();
}
};
解题描述
这道题题意是给出一个数字串,然后根据数字串在九宫格键盘上的位置找出所有可能的字母组合。解法上用到的是类似哈希和DP的办法。
不过这道题还可以用回溯的办法来解决,可以减少空间消耗,时间复杂度是差不多的:
class Solution {
private:
vector<string> alphaMap;
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.empty())
return res;
alphaMap = {
" ",
" ", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"
};
string path;
backTracking(res, path, digits, 0);
return res;
}
void backTracking(vector<string>& res, string& path, const string& digits, int index) {
if (index == digits.size()) {
res.push_back(path);
} else {
const string& alphas = alphaMap[digits[index] - '0'];
for (auto c : alphas) {
path.push_back(c);
backTracking(res, path, digits, index + 1);
path.pop_back();
}
}
}
};