LeetCode 0842. Split Array into Fibonacci Sequence Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0842. Split Array into Fibonacci Sequence

Description

You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579].

Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:

  • 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
  • f.length >= 3, and
  • f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.

Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.

Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.

 

Example 1:

Input: num = "1101111"
Output: [11,0,11,11]
Explanation: The output [110, 1, 111] would also be accepted.

Example 2:

Input: num = "112358130"
Output: []
Explanation: The task is impossible.

Example 3:

Input: num = "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.

 

Constraints:

  • 1 <= num.length <= 200
  • num contains only digits.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def splitIntoFibonacci(self, num: str) -> List[int]: def dfs(i): if i == n: return len(ans) > 2 x = 0 for j in range(i, n): if j > i and num[i] == '0': break x = x * 10 + int(num[j]) if x > 2**31 - 1 or (len(ans) > 2 and x > ans[-2] + ans[-1]): break if len(ans) < 2 or ans[-2] + ans[-1] == x: ans.append(x) if dfs(j + 1): return True ans.pop() return False n = len(num) ans = [] dfs(0) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !