Tuesday, February 11, 2014

[leetcode][****] Letter Combinations


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.
Basics:
1. string construction from char. string s(size_t n, char c).(Fills the string with n consecutive copies of character c.)
2. Switch: 
switch(variable){
  case(xx): xxx; break;
  ....
  default: xxx;
}

Algorithm:
Recursion Solve the problem.

My Code
string getChars(char a){
        switch(a){
        case('0'): return " ";
        case('2'): return "abc";
        case('3'): return "def";
        case('4'): return "ghi";
        case('5'): return "jkl";
        case('6'): return "mno";
        case('7'): return "pqrs";
        case('8'): return "tuv";
        case('9'): return "wxyz";
        default: return "";
    }
 }
    vector<string> RBuild(vector<string> str){
        vector<string> ret;
        if(str.empty()) return ret;
        string cur = str[0];
        str.erase(str.begin());
        vector<string> nxt = RBuild(str);
        if(nxt.empty()){
            for(int i = 0; i < cur.size(); ++i){
                string a(1, cur[i]);
                ret.push_back(a);
            }
            return ret;
        }else{
            for(int i = 0; i < cur.size(); ++i){    
                for(int j = 0; j < nxt.size(); ++j){
                    string a = cur[i]+nxt[j];
                    ret.push_back(a);
                }
            }
            return ret;
        }
    }
    vector<string> letterCombinations(string digits) {
        vector<string> ret;
        if(digits.empty()) {
            ret.push_back("");
            return ret;
        }
        vector<string> v;
        for(int i = 0; i < digits.length(); ++i){
            string str = getChars(digits[i]);
            if(str != ""){
                v.push_back(str);
            }
        }
        ret = RBuild(v);
        return ret;
       
    }

No comments:

Post a Comment