17. 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.
给定一串手机按键数字序列,要求给出所有可能的字符串组合。本题实质是一个搜索问题,DFS算法如下:
class Solution {
public:
void dfs(string& digits, int step, vector<string>& alphabeta, vector<string>& ans, bool is_first)
{
if (step == digits.size())
return;
string cur = alphabeta[digits[step] – ‘0’];
if (is_first) {
for (int i = 0; i < cur.size(); i++)
ans.push_back(cur.substr(i, 1));
is_first = false;
}
else {
int sz = ans.size(); //size要提前抽出来
for (int i = 0; i < sz; i++) {
string tmp = ans[i];
ans[i] = ans[i] + cur.substr(0, 1);
for (int j = 1; j < cur.size(); j++)
ans.push_back(tmp + cur.substr(j, 1));
}
}
dfs(digits, step + 1, alphabeta, ans, is_first);
}
vector<string> letterCombinations(string digits)
{
vector<string> alphabeta = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> ans;
dfs(digits, 0, alphabeta, ans, true);
return ans;
}
};
本代码提交AC,用时0MS。
本题当然也可以用BFS做。
二刷:
原来解法有一个is_first,而且for循环里处理不够优雅,这一题明显可以用一种更漂亮、统一的方法,代码如下:
class Solution {
private:
void dfs(string& digits, int step, vector<string>& alphabeta, vector<string>& ans, string& candidate)
{
if (step == digits.size()) {
ans.push_back(candidate);
return;
}
int idx = digits[step] – ‘0’;
for (int i = 0; i < alphabeta[idx].size(); ++i) {
candidate.push_back(alphabeta[idx][i]);
dfs(digits, step + 1, alphabeta, ans, candidate);
candidate.pop_back();
}
}
public:
vector<string> letterCombinations(string digits)
{
if (digits == "")
return {};
vector<string> alphabeta = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> ans;
string candidate = "";
dfs(digits, 0, alphabeta, ans, candidate);
return ans;
}
};
本代码提交AC,用时0MS。