LeetCode之Letter Combinations of a Phone Number

/*方法一:迭代求解法。这里类似于模拟,每次考虑添加数字对应的字母,当字母的
个数n大于1时,需要给结果中增加n-1个string,以作为结果。*/
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        string digit_strings[10] = {" ", " ", "abc", "def", "ghi",
            "jkl", "mno", "pqrs", "tuv", "wxyz"};
        vector<string> res;
        if(digits.empty()) return res;

        res.push_back(string(""));
        for(int i = 0; i < digits.size(); ++i){
            int size = res.size();
            for(int n = 0; n < size; ++n){
                for(int j = 1; j < digit_strings[digits[i]-'0'].size(); ++j){
                    res.push_back(res[n]);
                    res[res.size()-1] += digit_strings[digits[i]-'0'][j];
                }
                res[n] += digit_strings[digits[i]-'0'][0];
            }
        }
        return res;
    }
};

/*方法二:递归法。采用深度搜索的方法,对当前的字母进行选择,然后再递归求解子数组的
combinations。*/
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        if(digits.empty()) return res;
        string path;
        letterCombinations(digits, res, path, 0);
        return res;
    }
    
    void letterCombinations(const string &digits, vector<string> &res, string &path, int cur){
        string digit_strings[10] = {" ", " ", "abc", "def", "ghi",
            "jkl", "mno", "pqrs", "tuv", "wxyz"};
        if(cur == digits.size()){
            res.push_back(path);
            return;
        }
        for(int i = 0; i < digit_strings[digits[cur]-'0'].size(); ++i){
            path += digit_strings[digits[cur]-'0'][i];
            letterCombinations(digits, res, path, cur+1);
            path.pop_back();
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值