Leetcode 842. Split Array into Fibonacci Sequence
Given a string S
of digits, let us split the string into a Fibonacci-like sequence such that:
0
itself.Return the sequence or an empty array if it is impossible to form such a sequence.
S
?
S
is at most 200 characters.We will use a backtracking approach to explore all possible ways to split the string into a valid Fibonacci sequence. Our constraints will ensure that:
#include <vector>
#include <string>
#include <algorithm>
class Solution {
public:
std::vector<int> splitIntoFibonacci(std::string S) {
std::vector<int> result;
backtrack(S, result, 0);
return result;
}
private:
bool backtrack(const std::string& S, std::vector<int>& result, size_t start) {
if (start == S.size() && result.size() >= 3) {
return true;
}
long long num = 0;
for (size_t i = start; i < S.size(); ++i) {
// Prevent numbers with leading zeros (except '0')
if (i > start && S[start] == '0') break;
num = num * 10 + (S[i] - '0');
// If the number exceeds the int limit, break
if (num > INT_MAX) break;
if (result.size() >= 2) {
long long sum = static_cast<long long>(result[result.size() - 1]) + result[result.size() - 2];
if (num < sum) continue;
if (num > sum) break;
}
result.push_back(static_cast<int>(num));
if (backtrack(S, result, i + 1)) {
return true;
}
result.pop_back();
}
return false;
}
};
S
.We optimize by breaking early on invalid conditions (leading zeroes, oversize numbers). This practical optimization bounds runtime effectively for given constraint lengths.
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?