Problem
An additive number is a string whose digits can form an 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, return true if it is an additive number or false otherwise.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Algorithm
Use DFS to solve the problem, keeping track of the previous two numbers on the path, and continue searching forward if the condition is met.
Code
python3
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
nlen = len(num)
def dfs(s, num1, num2, cnts):
if s == nlen:
return cnts >= 3
for i in range(s, nlen):
if s < i and num[s] == '0':
break
num3 = int(num[s:i+1])
if cnts >= 2 and num3 != num1 + num2:
continue
if dfs(i+1, num2, num3, cnts+1):
return True
return False
return dfs(0, 0, 0, 0)