题目
约束
解法
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> combinations;
if (digits.empty()) {
return combinations;
}
unordered_map<char, string> phoneMap{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
string combination;
backtrack(combinations, phoneMap, digits, 0, combination);
return combinations;
}
void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) {
if (index == digits.length()) {
combinations.push_back(combination);
} else {
char digit = digits[index];
const string& letters = phoneMap.at(digit);
for (const char& letter: letters) {
combination.push_back(letter);
backtrack(combinations, phoneMap, digits, index + 1, combination);
combination.pop_back();
}
}
}
};
class Solution {
public:
string tmp;
vector<string> res;
vector<string> board={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
void DFS(int pos,string digits){
if(pos==digits.size()){
res.push_back(tmp);
return;
}
int num=digits[pos]-'0';
for(int i=0;i<board[num].size();i++){
tmp.push_back(board[num][i]);
DFS(pos+1,digits);
tmp.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits.size()==0) return res;
DFS(0,digits);
return res;
}
};
标签:digits,return,string,combination,dfs,combinations,phoneMap,字母组合,empty
From: https://www.cnblogs.com/chuixulvcao/p/17072370.html