LeetCode 91. Decode Ways

LeetCode 91. Decode Ways


A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

给定一个数字字符串,找出其中可以转换成字母的各种数字的组合,最后输出转化方案数目。


递归回溯法:(超时)

class Solution {
public:
    int numDecodings(string s) {
        int max = s.size();
        int ans = 0;
        find(s,ans,0,0,max);
        return ans;
    }
    void find(string s,int &ans,int cur,int len,int max){
        if(cur+len>max){return;}
        if(len!=0&&cur<max){
            string tmp;
            tmp.assign(s,cur,len);//就算len超出界限也会取得到
            if(tmp[0] == '0') return;
            int judge = atoi(tmp.c_str());//atoi的参数要求是char*
            if(judge>=1&&judge<=26){
                //cout<<cur<<"  "<<judge<<endl;
                cur+=len;
            }else{
                return;
            }
        }
        find(s,ans,cur,1,max);
        find(s,ans,cur,2,max);
        if(cur==max){
            ans++;
            return;
        }
    }

};

其实这题应该用动态规划法求解的。但自己又想不明白。所以就去找到自己能理解的一种动态规划算法,先看一遍,读懂后再自己重构一边,之前的dfs也是这么学习的。

class Solution {
public:
    int numDecodings(string s) {
        int len = s.size();
        vector<int> ans(len,0);
        if(s[0]!='0'){
            ans[0] = 1;
        }else{
            ans[0] = 0;
        }
        string tmp = s.substr(0,2);
        int num = stoi(tmp);
        if(num>=11&&num<=19 || num>=21&&num<=26) ans[1] = 2;
        else if(num == 10 || num == 20) ans[1] = 1;
        else if(num>=27 && tmp[1]!='0') ans[1] = 1;//30,40...都不行

        for(int i=2;i<len;i++){
            if(s[i]>='1'&&s[i]<='9'){
                ans[i] += ans[i-1];
            }
            if(s[i-1]=='1'||s[i-1] == '2'&&s[i]<'7'){
                ans[i] += ans[i-2];
            }
        }
        return ans[len-1];
    }

};

类似背包问题,从最底层开始向里面添加内容,添加到最高层时答案就出现了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值