Algorithm


Problem Name: 306. Additive Number

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.

 

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

 

Constraints:

  • 1 <= num.length <= 35
  • num consists only of digits.

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const isAdditiveNumber = function(num) {
  const n = num.length
  for (let i = 1; i  < = (n / 2) >> 0; ++i) {
    if (num.charAt(0) === '0' && i > 1) return false
    const x1 = +num.slice(0, i)
    for (let j = 1; Math.max(j, i)  < = n - i - j; ++j) {
      if (num.charAt(i) == '0' && j > 1) break
      const x2 = +num.slice(i, i + j)
      if (isValid(x1, x2, j + i, num)) return true
    }
  }
  return false
}

function isValid(x1, x2, start, num) {
  if (start === num.length) return true
  x2 = x2 + x1
  x1 = x2 - x1
  const sum = x2 + ''
  return num.startsWith(sum, start) && isValid(x1, x2, start + sum.length, num)
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
"112358"

Output

x
+
cmd
true

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isAdditiveNumber(self, num):
        def getStarter():
            arr = []
            for i in range(1, len(num) - 1):
                for j in range(i + 1, len(num)):
                    s1, s2 = num[:i], num[i:j]
                    if (s1[0] == "0" and len(s1) > 1) or (s2[0] == "0" and len(s2) > 1): 
                        continue
                    arr.append((int(s1), int(s2), j))
            return arr                 
        def dfs(pre1, pre2, i):
            if i == len(num):
                return True
            sm = pre1 + pre2
            l = len(str(sm))
            new = int(num[i:i + l])
            return new == sm and dfs(pre2, new, i + l)
        q = getStarter()
        return any(dfs(p1, p2, i) for p1, p2, i in q)
Copy The Code & Try With Live Editor

Input

x
+
cmd
"112358"

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#304 Leetcode Range Sum Query 2D - Immutable Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#307 Leetcode Range Sum Query - Mutable Solution in C, C++, Java, JavaScript, Python, C# Leetcode