Additive Number
要点:基本是道实现题,主要看错误点
错误点:
- 最内循环的结构:每次计算和以后都有一个新结果,比较新结果和当前下标下的,这样不断的roll over。这里用了先比较再更新的下标更新方式。最终如果更新后下标超出,说明找到解,如果在比较的时候超出string长度范围,则当前的和是不可行的
- 注意java string.substring的upper limit是exclusive的
- k到下一个位置的更新是+=len
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
def helper(num, n1, n2):
#print num, n1, n2
k = 0
while k<len(num):
res = int(n1)+int(n2)
n3 = str(res)
if n3 != num[k:k+len(n3)]:
return False
k+=len(n3)
n1 = n2
n2 = n3 # error 3: should be int()
return True
for i in range(2,len(num)//3*2+1): # not an error2: i is +1 more than right index
for j in range(1, i):
num1 = num[:j]
num2 = num[j:i]
if len(num1)>1 and num[0]=='0': continue
if len(num2)>1 and num[j]=='0': continue
# error 1: j is +1 more than right index
if helper(num[i:], num1, num2):
return True
return False