题解
又是双指针 of course no
回溯法
把数字和相应的字符一一对应
比如当第一个数字对应的第一个字符,然后就索引下一个数字,查找他所对应的字符,这样就可以把字符一一对应完
其实思路还是比较简单地,感觉暴力应该也可以
代码
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();
}
}
}
};