LeetCode-Decode Ways-编码方式-简单DP计数问题

https://oj.leetcode.com/problems/decode-ways/

一个DP计数的问题。解决思路就是假定后n-p个数的译码方式确定了,求前p个数的译码方式。

这样对s[p-1],s[p-2]进行合理性检查并决定能否规约到子问题即可。

我用了Memo的方法,DP也是一样的。

class Solution {
public:
    int n,m;
    vector <int> dp;
    string s;
    int Solve(int p){
        if (p==0){return 1;}
        if (dp[p]!=-1){return dp[p];}
        int res=0;
        if (s[p-1]!='0'){
            res+=Solve(p-1);    
        }
        if (p>1){
            int a=s[p-2]-'0';
            int b=s[p-1]-'0';
            int c=a*10+b;
            if (c>0 && c<=26 && a>0){
                res+=Solve(p-2);
            }
        }
        dp[p]=res;
        return res;
    }
    int numDecodings(string s) {
        n=s.length();
        this->s=s;
        dp.resize(n+1,-1);
        if (n==0){return 0;}
        return Solve(n);
    }
};

  

转载于:https://www.cnblogs.com/yangsc/p/4004788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值