动态规划_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")








猜你喜欢

转载自www.cnblogs.com/lux-ace/p/10546494.html