Skip to content

Commit ee9e8f4

Browse files
committed
Add solution #842
1 parent 9c1f520 commit ee9e8f4

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,7 @@
649649
839|[Similar String Groups](./0839-similar-string-groups.js)|Hard|
650650
840|[Magic Squares In Grid](./0840-magic-squares-in-grid.js)|Medium|
651651
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
652+
842|[Split Array into Fibonacci Sequence](./0842-split-array-into-fibonacci-sequence.js)|Medium|
652653
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
653654
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
654655
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 842. Split Array into Fibonacci Sequence
3+
* https://leetcode.com/problems/split-array-into-fibonacci-sequence/
4+
* Difficulty: Medium
5+
*
6+
* You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like
7+
* sequence [123, 456, 579].
8+
*
9+
* Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:
10+
* - 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
11+
* - f.length >= 3, and
12+
* - f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.
13+
*
14+
* Note that when splitting the string into pieces, each piece must not have extra leading zeroes,
15+
* except if the piece is the number 0 itself.
16+
*
17+
* Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
18+
*/
19+
20+
/**
21+
* @param {string} num
22+
* @return {number[]}
23+
*/
24+
var splitIntoFibonacci = function(num) {
25+
const result = [];
26+
const MAX_INT = 2 ** 31 - 1;
27+
backtrack(0);
28+
return result;
29+
30+
function backtrack(index) {
31+
if (index === num.length && result.length >= 3) return true;
32+
for (let length = 1; length <= num.length - index; length++) {
33+
if (num[index] === '0' && length > 1) break;
34+
const current = parseInt(num.substring(index, index + length));
35+
if (current > MAX_INT) break;
36+
if (result.length >= 2) {
37+
const sum = result[result.length - 1] + result[result.length - 2];
38+
if (current > sum) break;
39+
if (current < sum) continue;
40+
}
41+
result.push(current);
42+
if (backtrack(index + length)) return true;
43+
result.pop();
44+
}
45+
return false;
46+
}
47+
};

0 commit comments

Comments
 (0)