|
| 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