Leetcode 842. Split Array into Fibonacci Sequence
Given a string num
that contains only digits, your task is to split it into a Fibonacci-like sequence, where a sequence is Fibonacci-like if:
num
starts with a digit sequence representing the first number in the sequence.The sequence should contain at least three numbers. Return any such sequence in the form of a list of integers, or return an empty list if no such sequence can be constructed.
Here is the function signature:
public List<Integer> splitIntoFibonacci(String num)
num
?
num
can be up to 200 digits.0
itself.-2^31
and 2^31 - 1
.To solve this problem, we can use a backtracking approach:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> splitIntoFibonacci(String num) {
List<Integer> result = new ArrayList<>();
if (backtrack(result, num, num.length(), 0, 0, 0)) {
return result;
}
return new ArrayList<>();
}
private boolean backtrack(List<Integer> result, String num, int length, int index, long sum, int prev) {
if (index == length) {
return result.size() >= 3;
}
long currLong = 0;
for (int i = index; i < length; i++) {
if (i > index && num.charAt(index) == '0') {
break;
}
currLong = currLong * 10 + num.charAt(i) - '0';
if (currLong > Integer.MAX_VALUE) {
break;
}
int curr = (int) currLong;
if (result.size() >= 2) {
if (curr < sum) {
continue;
} else if (curr > sum) {
break;
}
}
result.add(curr);
if (backtrack(result, num, length, i + 1, prev + curr, curr)) {
return true;
}
result.remove(result.size() - 1);
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.splitIntoFibonacci("123456579")); // Output: [123, 456, 579]
}
}
The time complexity of this approach is O(2^N), where N is the length of the input string num
. This is because in the worst case, every character in the string could potentially start a new number in the sequence.
Note: To improve efficiency in practice, early pruning helps to skip invalid or impossible segments quickly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?