Skip to content

Commit c4a41eb

Browse files
committed
Add solution #306
1 parent cd95321 commit c4a41eb

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@
230230
292|[Nim Game](./0292-nim-game.js)|Easy|
231231
295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard|
232232
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
233+
306|[Additive Number](./0306-additive-number.js)|Medium|
233234
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
234235
322|[Coin Change](./0322-coin-change.js)|Medium|
235236
326|[Power of Three](./0326-power-of-three.js)|Easy|

solutions/0306-additive-number.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 306. Additive Number
3+
* https://leetcode.com/problems/additive-number/
4+
* Difficulty: Medium
5+
*
6+
* An additive number is a string whose digits can form an additive sequence.
7+
*
8+
* A valid additive sequence should contain at least three numbers. Except for the first two
9+
* numbers, each subsequent number in the sequence must be the sum of the preceding two.
10+
*
11+
* Given a string containing only digits, return true if it is an additive number or false
12+
* otherwise.
13+
*
14+
* Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or
15+
* 1, 02, 3 is invalid.
16+
*/
17+
18+
/**
19+
* @param {string} num
20+
* @param {Array} group
21+
* @param {number} startIndex
22+
* @return {boolean}
23+
*/
24+
var isAdditiveNumber = function(num, group = [], startIndex = 0) {
25+
if (startIndex === num.length && group.length >= 3) {
26+
return true;
27+
}
28+
29+
for (let i = startIndex; i < num.length; i++) {
30+
if (num[startIndex] === '0' && i !== startIndex) {
31+
break;
32+
}
33+
const n = +num.slice(startIndex, i + 1);
34+
if (group[group.length - 1] + group[group.length - 2] !== n && group.length >= 2) {
35+
continue;
36+
}
37+
group.push(n);
38+
if (isAdditiveNumber(num, group, i + 1)) {
39+
return true;
40+
}
41+
group.pop();
42+
}
43+
44+
return false;
45+
};

0 commit comments

Comments
 (0)