Tuesday, April 30, 2013

Letter Combinations of a Phone Number (C++ code)

LeetCode Letter Combinations of a Phone Number, Jan 27 '12
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"].
2->a,3->d 
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

void findpath(string &digits, int level, string &path, vector<string> &res, vector<string> &v){
       if(level == digits.length()) {
          res.push_back(path);
          return;
       }
      if(digits[level] == 1 || digits[level] == 0) findpath(digits,level+1,path,res,v);
      else{
         for(int i = 0; i < v[digits[level]].length(); i++){
          path.push_backdigits[level][i]);
          findpath(digits,level+1,path,res,v);
          path.pop_back();
        }
      }
}

 vector<string> letterCombinations(string digits) {
       vector<string> res;
       string path;
       vector<string> v(10);
       v[1] = "abc";
       v[2] = "def";
       v[3] = "ghi";
       v[4] = "jkl";
       v[5] = "mno";
       v[6] = "pqrs";
       v[7] = "tuv";
       v[8] = "wxyz";
       findpath(digits, 0, path, res, v);
    
       return res;
    }

No comments:

Post a Comment