问题描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
思路
深搜,直接搜就好,也没有什么好优化的
AC代码
class Solution {
public:
vector<string> res;
string strs[10] = {
"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxzy"
};
vector<string> letterCombinations(string digits) {
if(digits.empty()) return res;
dfs(digits, 0, "");
return res;
}
void dfs(string &digits, int u, string path) {
if (u == digits.size()) res.push_back(path);
else {
for (auto c: strs[digits[u] - '0'])
dfs(digits, u + 1, path + c);
}
}
};