标签:
遍历所有的可能。
1 class Solution { 2 private: 3 vector<string> res; 4 map<char,string> num; 5 public: 6 void initial() 7 { 8 9 num[‘2‘]="abc"; 10 num[‘3‘]="def"; 11 num[‘4‘]="ghi"; 12 num[‘5‘]="jkl"; 13 num[‘6‘]="mno"; 14 num[‘7‘]="pqrs"; 15 num[‘8‘]="tuv"; 16 num[‘9‘]="wxyz"; 17 } 18 19 void dfsdigits(int layer,int depth,string digits,string ans) 20 { 21 if(layer==depth) 22 { 23 res.push_back(ans); 24 return ; 25 } 26 for(int i=0;i<num[digits[layer]].size();i++) 27 { 28 dfsdigits(layer+1,depth,digits,ans+num[digits[layer]][i]); 29 } 30 } 31 vector<string> letterCombinations(string digits) { 32 if(digits.empty()) return res; 33 initial(); 34 35 dfsdigits(0,digits.size(),digits,""); 36 return res; 37 } 38 39 };
下面这种是循环,设中间变量
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; string num[10]={"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; if(digits.empty()) return res; res.push_back(""); for(int i=0;i<digits.size();i++) { vector<string> temp; for(int j=0;j<num[digits[i]-‘0‘].size();j++) for(int k=0;k<res.size();k++) temp.push_back(res[k]+num[digits[i]-‘0‘][j]); res=temp; } return res; } };
Letter Combinations of a Phone Number
标签:
原文地址:http://www.cnblogs.com/daocaorenblog/p/5232297.html