Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
该题题解主要要找到应该从哪儿开始循环,从解来看,最外层循环应该是上次解的集合,里面的循环是数字所对应的字符。
通过vector临时存储当前循环的解。
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> num_to_string ={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
int len = digits.length();
vector<string> result;
if(len==0)return result;
result.push_back("");
for(int i=0;i<len;i++){
int num=digits[i]-'0';
int len_num=num_to_string[num].size();
vector<string> tmp;//临时集合
for(int j=0;j<len_num;j++){
int len_result=result.size();
for(int k=0;k<len_result;k++){
tmp.push_back(result[k]+num_to_string[num][j]);
}
}
result=tmp;
}
return result;
}
};