leetcode-Letter Combinations of a Phone Number-17
输入一组数字,根据手机九宫格上每个数字对应的字母,输出这组数字能代表的所有字母的组合。
dfs,回溯。
1 class Solution { 2 private: 3 map<char,vector<char> > v; 4 public: 5 Solution(){ 6 v['2'].push_back('a'); 7 v['2'].push_back('b'); 8 v['2'].push_back('c'); 9 v['3'].push_back('d'); 10 v['3'].push_back('e'); 11 v['3'].push_back('f'); 12 v['4'].push_back('g'); 13 v['4'].push_back('h'); 14 v['4'].push_back('i'); 15 v['5'].push_back('j'); 16 v['5'].push_back('k'); 17 v['5'].push_back('l'); 18 v['6'].push_back('m'); 19 v['6'].push_back('n'); 20 v['6'].push_back('o'); 21 v['7'].push_back('p'); 22 v['7'].push_back('q'); 23 v['7'].push_back('r'); 24 v['7'].push_back('s'); 25 v['8'].push_back('t'); 26 v['8'].push_back('u'); 27 v['8'].push_back('v'); 28 v['9'].push_back('w'); 29 v['9'].push_back('x'); 30 v['9'].push_back('y'); 31 v['9'].push_back('z'); 32 } 33 void dfs(string s,int i,int j,vector<string> &ans,string ss){ 34 if(i==s.size()||j==v[s[i]].size()) return; 35 ss+=v[s[i]][j]; 36 if(i==s.size()-1){ 37 ans.push_back(ss); 38 return; 39 } 40 for(int k=0;k<v[s[i+1]].size();k++) dfs(s,i+1,k,ans,ss); 41 } 42 vector<string> letterCombinations(string digits) { 43 vector<string> ans; 44 if(digits.size()==0) return ans; 45 string s; 46 for(int i=0;i<v[digits[0]].size();i++) dfs(digits,0,i,ans,s); 47 return ans; 48 } 49 };