zoukankan      html  css  js  c++  java
  • leetcode--91--递归与动态规划

    题目链接:https://leetcode.com/problems/decode-ways/#/description

    第一种解法:递归,超时。。

    var numDecodings = function(s) {
      if(!s || s.match('00') || /^0/.test(s)){ 
        return 0;
      }else {
        return getNum(s);
      }
    };
    
    function getNum(s){
      if(/^0/.test(s)){
        return 0;
      }else if(s < 11){
        return 1;
      }else if(s <27){
        if(s%10 === 0)
          return 1;
        else
          return 2;
      }else if(s < 100){
        if(s%10 === 0)
          return 0;
        else
          return 1;
      }else {
        var headNum = s.substr(0,2);
        if(/^0/.test(headNum) || (headNum%10 === 0 && headNum>26)){
          return 0;
        }else if(headNum < 27){
          return getNum(s.substr(2)) + getNum(s.substr(1));  
        }else{
          return getNum(s.substr(1));
        }
      }
    }
    

      第二种:动态规划,通过

    function numDecodings(s){   
        if(!s || s.match('00') || /^0/.test(s))
            return 0;
        var dp = [1];
        dp[1] = s.charAt(0) == '0' ? 0 : 1;
    
        for(var i = 2; i <= s.length; i++){
            dp[i] = 0;
            // 如果字符串的第i-1位和第i位能组成一个10到26的数字,说明我们可以在第i-2位的解码方法上继续解码
            if(s.substring(i-2, i) <= 26 && s.substring(i-2, i) >= 10){
                dp[i] += dp[i - 2]; 
            }
            if(s.substring(i-1, i) != '0'){
                dp[i] += dp[i - 1]; 
            }
        }
        return dp[s.length];
    }
  • 相关阅读:
    决策树算法系列之一 ID3
    线性递归数列算法题
    Python爬虫快速上手教程
    gensim快速上手教程
    GCN和GCN在文本分类中应用
    命名实体如何进行概念消歧?
    浅谈神经网络中的激活函数
    nginx安装配置和基本使用
    netty学习总结(三)
    netty学习总结(二)
  • 原文地址:https://www.cnblogs.com/wangxuehao/p/6729006.html
Copyright © 2011-2022 走看看