Leetcode 306. Additive Number

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.

1 + 99 = 100, 99 + 100 = 199

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.

我一开始想到了用DP。但是无法写出递推函数。其实本题用类似brute force的搜索可以通过OJ。本题学习了两个Python内嵌的函数,一个是itertools.combination(list, num)。可以列出list中取num个数字的所有combination而且没有重复。

另外一个是 string1.startswith(string2, beg, end)。这个函数可以检查string1的从beg开始长度为end的sub string是不是以string2开头。

     def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
n = len(num)
for i, j in itertools.combinations(range(1, n), 2):
a, b = num[:i], num[i:j]
if a != str(int(a)) or b != str(int(b)):
continue
while j < n:
c = str(int(a)+int(b))
if num.startswith(c, j):
j += len(c)
a, b = b, c
else:
break
if j == n:
return True
return False

本题还可以用递归的解法

上一篇:【Unity3D】Invoke,InvokeRepeating ,Coroutine 延迟调用,周期性调用


下一篇:开发iOS应用程序需要的工具和编程技术