Letter Combinations of a Phone Number

来源:互联网 发布:office fix it 2007 编辑:程序博客网 时间:2024/06/06 16:30
-----QUESTION-----

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.

Letter <wbr>Combinations <wbr>of <wbr>a <wbr>Phone <wbr>Number

Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

-----SOLUTION-----

class Solution {public:    vector<string> letterCombinations(string digits) {        digitLetter.clear();        result.clear();        createMap();        string str = "";        dfs(digits, 0, str);        return result;    }    void dfs(const string &digits, int depth, string &str)    {        if(depth == digits.length())        {            result.push_back(str);            return;        }        int num = digits[depth]-'0';        for(int j = 0; j < digitLetter[num].length(); j++)        {            str+=digitLetter[num][j];            dfs(digits, depth+1, str);            str.erase(str.end()-1);        }            }    void createMap()    {        digitLetter[2] = "abc";        digitLetter[3] = "def";        digitLetter[4] = "ghi";        digitLetter[5] = "jkl";        digitLetter[6] = "mno";        digitLetter[7] = "pqrs";        digitLetter[8] = "tuv";        digitLetter[9] = "wxyz";    }private:    map<int,string> digitLetter;    vector<string> result;};


0 0
原创粉丝点击