class Solution {
public:
vector<string> letterCombinations(string digits) {
//定义所有输出结果
vector<string> conbinations;
if(digits.empty()){
return conbinations;
}
//定义手机号对应的字母
unordered_map<char,string>phonemap{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
//定义输出结果的一种
string conbination;
backtrack(conbinations,phonemap,digits,0,conbination);
return conbinations;
}
void backtrack(vector<string>& conbinations,const unordered_map<char,string>&phonemap,string&digits,int index,string&conbination){
//结束循环条件,把所有输出结果压入到conbinnations
if(index==digits.length()){
conbinations.push_back(conbination);
}else{
//输出对应数字
char digit=digits[index];
//取出数字对应的字符串 string .at()用于获取指定字符
const string&letters =phonemap.at(digit);
//进行循环,压入字符
for(const char&letter:letters){
//压入字符
conbination.push_back(letter);
backtrack(conbinations,phonemap,digits,index+1,conbination);
//弹出字符,继续循环
conbination.pop_back();
}
}
}
};
17. 电话号码的字母组合
最新推荐文章于 2024-09-03 11:25:36 发布