標籤:檢查 leading als 遞推 log term 沒有 bool form
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 continue11 while j < n:12 c = str(int(a)+int(b))13 if num.startswith(c, j):14 j += len(c)15 a, b = b, c16 else:17 break18 if j == n:19 return True20 return False
本題還可以用遞迴的解法
Leetcode 306. Additive Number