题目链接
解法
本题采用回溯算法,或者我们把它叫深搜吧。
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
2对应着abc,3对应着def,那么我们从a为起点开始走,依次找到ad, ae, af三条路;在以b为起点开始走…
走完所有的路径,就是我们想要的答案了。
代码
class Solution {
public:
vector<string> ans;
string strs[10] = {
"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz",
};
vector<string> letterCombinations(string digits) {
if (digits.empty()) return ans;
dfs(digits, 0, "");
return ans;
}
void dfs(string &digits, int u, string path) {
if (u == digits.size()) ans.push_back(path);
else {
for (auto c: strs[digits[u] - '0'])
dfs(digits, u + 1, path + c);
}
}
};