leetcode[17]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.

class Solution {
public:
void createMap(map<char,string> &dMap)
{
    dMap['0']="";
    dMap['1']="";
    dMap['2']="abc";
    dMap['3']="def";
    dMap['4']="ghi";
    dMap['5']="jkl";
    dMap['6']="mno";
    dMap['7']="pqrs";
    dMap['8']="tuv";
    dMap['9']="wxyz";
    return;
}
void dfsDigits(int curDeep, vector<string> &res, string currStr, const string digits, map<char,string> dMap)
{
    if (curDeep==digits.size())
    {
        res.push_back(currStr);
        return;
    }    
    for (int i=0; i<dMap[digits[curDeep]].size();i++)
    {
        dfsDigits(curDeep+1, res, currStr+dMap[digits[curDeep]][i], digits, dMap);
    }
}
vector<string> letterCombinations(string digits) 
{
    vector<string> res;
    const int len=digits.size();
    map<char,string> dMap;
    createMap(dMap);
    dfsDigits(0, res, "", digits, dMap);
    return res;
}
};

 

posted @ 2015-02-10 13:40  Vae永Silence  阅读(205)  评论(0)    收藏  举报