zoukankan      html  css  js  c++  java
  • 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 an encoded message containing digits, determine the total number of ways to decode it.
    
    For example,
    Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
    
    The number of ways decoding "12" is 2.

    思路:本题解码,不用输出编码结果,而只是让你找出有多少种解码方法,故此题可以使用动态规划。初始状态dp[0]=1,dp[1]=1(当s[0]!='0');dp[1]=0(s[0]=='0')

    状态转移方程dp[i]+=dp[i-1](1~9);dp[i]+=dp[i-2](10~26);

    class Solution {
    public:
        int numDecodings(string s) {
            int n=s.size();
            if(n<=0)
                return 0;
            vector<int> dp(n+1,0);
            dp[0]=1;
            if(s[0]=='0')
                dp[1]=0;
            else
                dp[1]=1;
            for(int i=2;i<=n;i++)
            {
                int num=stoi(s.substr(i-1,1));
                if(num>0 && num<=9)
                    dp[i]+=dp[i-1];
                num=stoi(s.substr(i-2,2));
                if(num>=10&&num<=26)
                    dp[i]+=dp[i-2];
            }
            return dp[n];
        }
    };
  • 相关阅读:
    子网掩码的作用与IP网段的划分
    DHCP服务器
    Anaconda安装、更新第三方包
    time模块的使用
    TensorFlow安装
    机器学习-线性回归
    机器学习
    Pyhton-类(2)
    python-类(1)
    Python-函数
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3825529.html
Copyright © 2011-2022 走看看