Leetcode 306. Additive Number
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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开头。
1 def isAdditiveNumber(self, num): 2 """ 3 :type num: str 4 :rtype: bool 5 """ 6 n = len(num) 7 for i, j in itertools.combinations(range(1, n), 2): 8 a, b = num[:i], num[i:j] 9 if a != str(int(a)) or b != str(int(b)): 10 continue 11 while j < n: 12 c = str(int(a)+int(b)) 13 if num.startswith(c, j): 14 j += len(c) 15 a, b = b, c 16 else: 17 break 18 if j == n: 19 return True 20 return False
本题还可以用递归的解法
以上是关于Leetcode 306. Additive Number的主要内容,如果未能解决你的问题,请参考以下文章