相关问题
17. Letter Combinations of a Phone Number
77. Combinations
Discription
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"].
思路
递归/深度优先搜索。
具体实现包括递归和非递归两种形式。
时间复杂度:
?
空间复杂度:
代码
递归
class Solution {
public:
void dfs(vector<string> &res, string str, int i, string &digits, vector<string> &map)
{
// 边界条件
cout << digits.size();
if (i == digits.size())
{
res.push_back(str);
return;
}
// 递归
for (int j = 0; j < map[digits[i] - '0'].size(); j++)
dfs(res, str + map[digits[i] - '0'][j], i + 1, digits, map);
}
vector<string> letterCombinations(string digits) {
vector<string> map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> res;
string str = "";
if (digits.size() == 0) return res;
dfs(res, str, 0, digits, map);
return res;
}
};
非递归
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> res;
if (digits.size() == 0) return res;
vector<string> map = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
queue<string> que;
que.push("");
for (int i = 0; i < digits.size(); i++) // digits中的第i个字符,如"234" 中的 "2"
{
int n = que.size();
for (int j = 0; j < n; j++) // 队列中的第j个字符串 "abca"
{
string str = map[digits[i] - '0'];
for (int k = 0; k < str.size(); k++) // digits中的第i个字符映射的字符串中第k个字符 "abc"的 "b"
que.push(que.front() + str[k]);
que.pop();
}
}
while(!que.empty())
{
res.push_back(que.front());
que.pop();
}
return res;
}
};