电话号码的字母组合

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

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

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();
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值