Saturday, September 20, 2014

LeetCode: Letter Combinations of a Phone Number

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.


   typedef vector<string> vs;  
   
   void letterCombinationsUtil(string digits, vs &res, vs &list, int cur, int n, string &s)  
   {  
     if(cur == n)  
     {  
       res.push_back(s);  
       return;  
     }  
     string &str = list[digits[cur] - '0'];  
     int x = str.length();  
     for (int i = 0; i < x; i++)  
     {  
       s[cur] = str[i];  
       letterCombinationsUtil(digits, res, list, cur+1, n, s);  
     }  
   }  
   
   vector<string> letterCombinations(string digits) {  
     vector<string> list = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};   
     vector<string> res;  
     int n = digits.length();  
     if(n == 0){res.push_back("");return res;}  
     string s;  
     for (int i = 0; i <n; i++)s += '0';  
     letterCombinationsUtil(digits, res, list, 0, n, s);  
     return res;  
   }  

No comments:

Post a Comment