Monday, November 25, 2013

LeetCode Problem : Letter Combinations of a Phone Number

Problem


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.

Code

typedef void(*func)();
class AAAA
{
public:
    AAAA(func foo)
    {
        foo();
    }
};

class Solution {
public:
    static map<char,string> keymap;
    static void init_keyMap()
    {
        keymap.insert(make_pair('1',""));keymap.insert(make_pair('2',"abc"));
        keymap.insert(make_pair('3',"def"));keymap.insert(make_pair('4',"ghi"));
        keymap.insert(make_pair('5',"jkl"));keymap.insert(make_pair('6',"mno"));
        keymap.insert(make_pair('7',"pqrs"));keymap.insert(make_pair('8',"tuv"));
        keymap.insert(make_pair('9',"wxyz"));keymap.insert(make_pair('0',""));
    }
    void dfs_lc(const string& s,const map<char,string> &keymap,
     string &out,int i,int pos,int n,vector<string> &result)
    {
        if(i == n){
            result.push_back(out);
            return;
        }
        char ch = s[i];
        string str = (keymap.find(ch))->second;//keymap[ch];
        for(int j =0;j < str.size();++j){
            out[pos] = str[j];
            dfs_lc(s,keymap,out,i+1,pos+1,n,result);
        }
    }
    vector<string> letterCombinations(string digits) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        static AAAA aaaa(init_keyMap);
        int n = digits.size();
        string out;
        out.resize(n);
        vector<string> result;
        dfs_lc(digits,keymap,out,0,0,n,result);
        return result;
    }
};

No comments:

Post a Comment