zoukankan      html  css  js  c++  java
  • 动态规划_leetcode91

    #coding=utf-8
    class Solution1(object):
    def numDecodings(self, s):
    """
    :type s: str
    :rtype: int

    """
    if not s:
    return

    return self.decode(s)

    pass

    def decode(self,s):


    if len(s) == 0:
    return 1

    if len(s) == 1:
    num = int(s[0])

    if num >= 1 and num <= 26:
    return 1

    return 0



    res = 0
    num1 = int(s[0])

    if num1 >= 1 and num1 <= 26:
    res += self.decode(s[1:])
    else:
    return res

    num2 = int(s[0:2])

    if num2 >= 1 and num2 <= 26:
    res += self.decode(s[2:])

    return res




    # s = Solution1()
    #
    # ts = "4757562545844617494555774581341211511296816786586787755257741178599337186486723247528324612117156948"
    #
    # print s.numDecodings(ts)


    # 记忆化递归不太好记录状态,直接使用动归
    # key 为数组确实不太好记状态 20190306
    class Solution3(object):
    def numDecodings(self, s):
    """
    :type s: str
    :rtype: int

    """
    if not s:
    return

    return self.decode(s)



    def decode(self,s):

    length = len(s)

    if length == 1:
    num = int(s[0])

    if num >= 1 and num <= 26:
    return 1

    return 0

    memo = [0 for i in range(length+1)]

    num1 = int(s[length-1])

    memo[length] = 1

    if num1 == 0:
    memo[length-1] = 0
    else:
    memo[length-1] = 1


    for i in range(length-2,-1,-1):

    num1 = int(s[i])

    if num1 == 0:
    memo[i] = 0
    continue

    num2 = int(s[i:i+2])

    if num2 >= 10 and num2 <= 26:
    memo[i] = memo[i+1]+ memo[i+2]
    else:
    memo[i] = memo[i+1]


    return memo[0]


    s = Solution3()

    print s.numDecodings("12")








  • 相关阅读:
    Python—设计模式
    Python—操作系统和多线程
    thin mission 2021 11 3
    搜索
    c++ 调试
    Lecture--words families
    高数--积分
    thin mission 2021.11.2
    tiny mission 2021.11.1
    zlib使用心得
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546494.html
Copyright © 2011-2022 走看看