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.
Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Example 1:
Input: "112358"
Output: true
Explanation: 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
Example 2:
Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Follow up:
How would you handle overflow for very large input integers?
class Solution: def isAdditiveNumber(self, num): """ :type num: str :rtype: bool """ if len(num)<=2: return False def judge(s): #judge a string valid or not if len(s)==1: return True if len(s)==0: return False if s[0]=='0': return False return True def solve(i,j): #judge this divided method vaild or not a,b = num[:i],num[i:j] if judge(a) is False or judge(b) is False: return False n1,n2 = int(a),int(b) # print(n1,n2) while True: n3 = n1 + n2 c = str(n3) if j+len(c)>len(num) or n3!=int(num[j:j+len(c)]): return False if j+len(c)==len(num): return True n1 = n2 n2 = n3 j = j+len(c) # print('n2:',n2,'n1:',n1,'j:',j) for i in range(1,len(num)//2+1): for j in range(i+1,len(num)): # print(i,j) if solve(i,j): return True return False
手動dfs 對於任一種情況,只要定下來前兩個數字,後邊就都是確定的了,所以只需要遍歷前兩個數字的所有情況。