https://www.cnblogs.com/grandyang/p/4452220.html
用迭代的方法,每次从3个字符中选择一个然后传给下一次迭代
index是遍历的digits的索引
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> output; if(digits.empty()) return output; string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; combination(digits,dict,0,"",output); return output; } void combination(string digits,string dict[],int index,string input,vector<string> &output){ if(index == digits.size()){ output.push_back(input); return; } string str = dict[digits[index] - '0']; for(int i = 0;i < str.size();i++) combination(digits,dict,index+1,input + str[i],output); } };
自己写的另一种写法:
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> result; if(digits.empty()) return result; string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; int start = 0; string res = ""; search(digits,result,res,dict,start); return result; } void search(string digits,vector<string>& result,string res,string dict[],int start){ if(start == digits.size()){ result.push_back(res); return; } string tmp = dict[digits[start] - '0']; for(int i = 0;i < tmp.size();i++){ res += tmp[i]; search(digits,result,res,dict,start+1); res.pop_back(); } } };