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








转载于:https://www.cnblogs.com/lux-ace/p/10546494.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值