动态规划_leetcode91

Posted AceKo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态规划_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")








以上是关于动态规划_leetcode91的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 91. Decode Ways 解码方法(动态规划,字符串处理)

Leetcode No.91 解码方法(动态规划)

Leetcode No.91 解码方法(动态规划)

LeetCode 91. 解码方法

LeetCode 0091.解码方法 - 动态规划+原地滚动(比较高效的算法)

动态规划_leetcode337