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:
    vector<string> ans;
    unordered_map<char,string> um;
    void dfs(string digits,vector<char> path, int pos){
        if (pos == digits.size()){
            string s;
            for(int i = 0; i < path.size();i++) s += path[i];
            ans.push_back(s);
            return;
        }
        string v = um[digits[pos]];
        for(int i = 0; i < v.size();i++){
            path.push_back(v[i]);
            dfs(digits,path,pos+1);
            path.resize(path.size() -1);
        }
    }
    vector<string> letterCombinations(string digits) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        um.insert(make_pair('2',"abc"));
        um.insert(make_pair('3',"def"));
        um.insert(make_pair('4',"ghi"));
        um.insert(make_pair('5',"jkl"));
        um.insert(make_pair('6',"mno"));
        um.insert(make_pair('7',"pqrs"));
        um.insert(make_pair('8',"tuv"));
        um.insert(make_pair('9',"wxyz"));
        vector<char> path;
        ans.clear();
        dfs(digits,path,0);
        return ans;
    }
};

 

posted @ 2013-07-14 19:44  一只会思考的猪  阅读(238)  评论(0编辑  收藏  举报