Leetcode:Letter Combinations of a Phone Number
Description:
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
分析: 非常有意思的题目,电话按键串可以凑成的所有字符串,因为每个按键对应着3个-4个字符串,故基本也是一个深搜问题,对按键串的每一次按键都
可以对应着某个字符,然后深搜每个按键数字,凑成最后的字符串。
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 map<char,string> phone; 5 phone.insert(make_pair('1',"")); 6 phone.insert(make_pair('2',"abc")); 7 phone.insert(make_pair('3',"def")); 8 phone.insert(make_pair('4',"ghi")); 9 phone.insert(make_pair('5',"jkl")); 10 phone.insert(make_pair('6',"mno")); 11 phone.insert(make_pair('7',"pqrs")); 12 phone.insert(make_pair('8',"tuv")); 13 phone.insert(make_pair('9',"wxyz")); 14 phone.insert(make_pair('0'," ")); 15 16 string oneres; 17 vector<string> result; 18 //if(digits.empty()) return result; 19 20 findresult(phone,digits,oneres,result,0); 21 return result; 22 } 23 void findresult(map<char,string> phone,string digits,string& oneres, vector<string>& result, int index) 24 { 25 if(index==digits.size()) 26 { 27 result.push_back(oneres); 28 //oneres.clear(); 29 return; 30 } 31 string mapto = (phone.find(digits[index]))->second; 32 for(int i=0;i<mapto.size();i++) 33 { 34 string back = oneres; 35 oneres += mapto[i]; 36 findresult(phone,digits,oneres,result,index+1); 37 oneres = back; 38 } 39 } 40 };