Lituo-- 91. Decoding method

Topic Link: 91. Decoding Method - LeetCode 

The following is to use the idea of ​​dynamic programming to solve this problem. If you are not very clear about the meaning of the five parts of dynamic programming, you can read the first question of this column . Use the minimum cost to climb the stairs_KOBE 0824 BRYANT's blog-CSDN blog , here is a more detailed analysis of the meaning of the five parts of dynamic programming, I believe that all of you can understand and master this question.

Reference Code:

class Solution {
public:
    int numDecodings(string s) {
        int n=s.size();
        //多开一个虚拟节点
        vector<int> dp(n+1);
        dp[0]=1;
        dp[1]=s[0]!='0';
        //如果s只有一个元素,那么应该直接返回
        if(n<2)
        {
            return dp[1];
        }
        //因为dp[0]和dp[1]已经填过了,所以从dp[2]开始填,因为多开了一个虚拟节点,所以应该填到dp[n]
        for(int i=2;i<=n;i++)
        {
            //这里写s[i-1]是调整了下标的映射关系,所有需要找s[i]的地方都要在原来的下标基础上减1
            //第一种情况
            if(s[i-1]!='0')
            {
                dp[i]+=dp[i-1];
            }
            int tmp=10*(s[i-2]-'0')+(s[i-1]-'0');
            //第二种情况
            if(tmp>=10&&tmp<=26)
            {
                dp[i]+=dp[i-2];
            }
        }
        return dp[n];
    }
};

The above is the whole process of analyzing this dp question. Although it is indeed a bit complicated, you can still learn to understand it step by step. Come on, believe in yourself, the rules of movement can be learned.

Have you learned it? If the solutions to the above questions are helpful to you, please highlight the following carefully and pay attention to them. We will continue to update the classic questions of dynamic programming in the future. See you in the next issue! ! ! !

Guess you like

Origin blog.csdn.net/weixin_70056514/article/details/131481058