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

  

posted @ 2014-10-03 10:54  zombies  阅读(160)  评论(0编辑  收藏  举报