电话号码的字母组合

来源:互联网 发布:查看python对象的函数 编辑:程序博客网 时间:2024/04/30 12:31

给一个数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。

下图的手机按键图,就表示了每个数字可以代表的字母。

Cellphone

样例

给定 "23"

返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

注意

以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。


 class Solution { public:    /**     * @param digits A digital string     * @return all posible letter combinations     */    vector<string> letterCombinations(string& digits) {        // Write your code here        int n = digits.length();        vector<string> result;        if (n < 1)        {            return result;        }        vector<string> buf;        buf.push_back("abc");        buf.push_back("def");        buf.push_back("ghi");        buf.push_back("jkl");        buf.push_back("mno");        buf.push_back("pqrs");        buf.push_back("tuv");        buf.push_back("wxyz");        vector<char> str;        visit(digits, n, buf, 0, result, str);        return result;    } private:    void visit(string &digits, int n, vector<string> &buf, int pos,                 vector<string> &result, vector<char> &str)    {        if (n == pos)        {            string temp;            for (int i = 0; i < n; i++)            {                temp += str[i];            }            result.push_back(temp);            return;        }        int k = digits[pos] - '2';        for (int i = 0; i < buf[k].length(); i++)        {            str.push_back(buf[k][i]);            visit(digits, n, buf, pos+1, result, str);            str.pop_back();        }    }};



0 0
原创粉丝点击