题目描述:
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/submissions/
思路:
代码实现:
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()) return {};
vector<string> res;//保存结果
vector<string> dict{"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//字典0-9数字对应的字符串
helper(digits, dict, 0,"", res);
return res;
}
void helper(string& digits, vector<string>& dict, int level, string out, vector<string>& res){
//res存放最终结果,out存放临时结果,level-生成的字符串大小,dict-字典
if(level == digits.size()) {//如果level和digit大小相等,输出out为最终结果
res.push_back(out);
return ;
}
string str = dict[digits[level] - '0'];//找到digit中数字对应的字符串
for(int i = 0; i < str.size(); i++){//遍历字符串
helper(digits, dict, level+1, out+str[i], res);
}
}
};
迭代:
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
vector<string> res{""};
vector<string> dict{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for(int i = 0; i < digits.size(); i++){
vector<string> t;
string str = dict[digits[i] - '0'];
for(int j = 0; j < str.size(); j++){
for(string s:res) t.push_back(s+str[j]);
}
res = t;
}
return res;
}
};