码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划_leetcode91

时间:2019-03-17 14:03:16      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:lse   动态   elf   else   turn   span   style   obj   +=   

#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

标签:lse   动态   elf   else   turn   span   style   obj   +=   

原文地址:https://www.cnblogs.com/lux-ace/p/10546494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!