class Solution {
public:
string path;
vector<string> res;
string dict[10] = {
"", "",
"abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz",
};
vector<string> letterCombinations(string digits) {
if (digits.empty()) return vector<string> (); //或者return res; 也行
dfs(digits, 0);
return res;
}
void dfs(string& digits, int u) {
if (u == digits.size()) {
res.push_back(path);
return ;
}
int ch = digits[u] - '0';
for (int i = 0; i < dict[ch].size(); i ++) {
string tmp = path;
path += dict[ch][i];
dfs(digits, u + 1);
path = tmp; // 恢复现场
}
}
};
yxc代码
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);
}
}
};