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.

    思路:

    使用动态规划,我在确定临界值方面出现错误。 

    sum[i] 表示 s[0....i-1] 的方法总数,首先设置sum[0]=1,如果s[0]为0,那么不能成为一种手段。

    整个的递推方式为:sum[i]=sum[i-1](倒数第一个不为0)+sum[i-2] (倒数第二个小于等于2,倒数第一个小于等于6).

    意思是:首先只要s[i-1]不为0,当前的数值等于前一个数值。

    如果倒数第二个小于等于2,倒数第一个小于等于6,那么还能够再加上前两个的数值。

    代码:

    class Solution {
    public:
        int numDecodings(string s) {
            //dp[i]  --  s[0..i-1]
            if(s.empty())   return 0;
            int len=s.length();
            int sum[len+1];
            
            sum[0]=1;
            sum[1]=s[0]=='0'?0:1;
            
            for(int i=2;i<=len;i++){
                if(s[i-1]=='0') sum[i]=0;
                else    sum[i]=sum[i-1];
                
                if( s[i-2]=='1'|| (s[i-2]=='2'&&s[i-1]<='6') )
                    sum[i]+=sum[i-2];
            }
            return sum[len];
        }
    };


  • 相关阅读:
    类模板机制
    C和C++中const的区别
    bitset
    静态库or动态库?
    多态原理探究
    程序从编译到运行过程
    对象的内存模型
    重载、重写(覆盖)和隐藏
    对继承和派生的理解
    对C++对象的理解
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519852.html
Copyright © 2011-2022 走看看