Additive Number
Description
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
Constraints:
num
consists only of digits'0'-'9'
.1 <= num.length <= 35
Follow up:
How would you handle overflow for very large input integers?
Solution(javascript)
/*
* @lc app=leetcode id=306 lang=javascript
*
* [306] Additive Number
*/
// @lc code=start
/**
* @param {string} num
* @return {boolean}
*/
const isAdditiveNumber = function (num) {
const invalid = (s = '') => s.length === 0 || (s[0] === '0' && s.length > 1)
const dfs = (a = '', b = '', str = '') => {
if (invalid(a) || invalid(b)) {
return false
}
if (str === '') {
return true
}
for (let i = 0; i < str.length; i++) {
const c = str.slice(0, i + 1)
if (!invalid(c) && parseInt(a, 10) + parseInt(b, 10) === parseInt(c, 10)) {
if (dfs(b, c, str.slice(i + 1))) {
return true
}
}
}
return false
}
for (let i = 1; i <= num.length - 2; i++) {
for (let j = i + 1; j <= num.length - 1; j++) {
if (dfs(num.slice(0, i), num.slice(i, j), num.slice(j))) {
return true
}
}
}
return false
}
// @lc code=end
// console.log(
// isAdditiveNumber(
// '199100199',
// ),
// )