Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/842.html
842. Split Array into Fibonacci Sequence
Level
Medium
Description
Given a string S
of digits, such as S = "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] <= 2^31 - 1
, (that is, each integer fits a 32-bit signed integer type);F.length >= 3
;- and
F[i] + F[i+1] = F[i+2]
for all0 <= i < F.length - 2
.
Also, 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 S
, or return []
if it cannot be done.
Example 1:
Input: “123456579”
Output: [123,456,579]
Example 2:
Input: “11235813”
Output: [1,1,2,3,5,8,13]
Example 3:
Input: “112358130”
Output: []
Explanation: The task is impossible.
Example 4:
Input: “0123”
Output: []
Explanation: Leading zeroes are not allowed, so “01”, “2”, “3” is not valid.
Example 5:
Input: “1101111”
Output: [110, 1, 111]
Explanation: The output [11, 0, 11, 11] would also be accepted.
Note:
1 <= S.length <= 200
S
contains only digits.
Solution
First check the maximum end index of the first number and the second number. Suppose the string contains only three numbers that form a Fibonacci-like sequence, then the third number can’t be shorter than either the first number of the second number. Suppose the length of string S
is length
, then the maximum end index of the first number is length / 2 - 1
and the maximum end index of the second number is length * 2 / 3 - 1
.
For each possible choice of the first number and the second number, try to form a Fibonacci-like sequence starting from the first number and the second number. If one choice can lead to a Fibonacci-like sequence that equals S
, return a list containing all the numbers in the sequence. Otherwise, return an empty list.
-
class Solution { public List<Integer> splitIntoFibonacci(String S) { List<Integer> list = new ArrayList<Integer>(); if (S == null || S.length() == 0) return list; int length = S.length(); int firstMax = Math.min(length / 2, 10), secondMax = Math.min(length * 2 / 3, 20); for (int i = 1; i <= firstMax; i++) { if (i > 1 && S.charAt(0) == '0' || Long.parseLong(S.substring(0, i)) > Integer.MAX_VALUE) break; int secondMaxUpper = Math.min(secondMax, i + 11); for (int j = i + 1; j <= secondMaxUpper; j++) { List<Integer> splitIndices = new ArrayList<Integer>(); String firstNumStr = S.substring(0, i); String secondNumStr = S.substring(i, j); splitIndices.add(i); splitIndices.add(j); if (secondNumStr.length() > 1 && secondNumStr.charAt(0) == '0') break; StringBuffer sb = new StringBuffer(firstNumStr + secondNumStr); int prevIndex = j; while (sb.length() < length) { long firstNum = Long.parseLong(firstNumStr); long secondNum = Long.parseLong(secondNumStr); long sum = firstNum + secondNum; if (sum > Integer.MAX_VALUE) break; String sumStr = String.valueOf(sum); sb.append(sumStr); int index = prevIndex + sumStr.length(); if (index < length) splitIndices.add(index); prevIndex = index; firstNumStr = secondNumStr; secondNumStr = sumStr; } if (sb.toString().equals(S)) { int size = splitIndices.size(); for (int k = size - 1; k >= 0; k--) { int splitIndex = splitIndices.get(k); sb.insert(splitIndex, ','); } String[] array = sb.toString().split(","); int sequenceLength = array.length; for (int k = 0; k < sequenceLength; k++) list.add(Integer.parseInt(array[k])); return list; } } } return list; } }
-
// OJ: https://leetcode.com/problems/split-array-into-fibonacci-sequence/ // Time: O(N!) // Space: O(N) class Solution { vector<int> ans; bool dfs(string &s, int i) { if (i == s.size()) return ans.size() >= 3; for (int j = i; j < s.size(); ++j) { long n = stol(s.substr(i, j - i + 1)); if (n > INT_MAX) return false; if (ans.size() >= 2) { long target = (long)ans.back() + ans[ans.size() - 2]; if (target > INT_MAX) return false; if (n == target) { ans.push_back(n); if (dfs(s, j + 1)) return true; ans.pop_back(); break; } if (n > target) break; } else { ans.push_back(n); if (dfs(s, j + 1)) return true; ans.pop_back(); } if (s[i] == '0') return false; } return false; } public: vector<int> splitIntoFibonacci(string s) { dfs(s, 0); return ans; } };
-
class Solution(object): def splitIntoFibonacci(self, S): """ :type S: str :rtype: List[int] """ res = [] self.dfs(S, [], res) return res def dfs(self, num_str, path, res): if len(path) >= 3 and path[-1] != path[-2] + path[-3]: return False if not num_str and len(path) >= 3: res.extend(path) return True for i in range(len(num_str)): curr = num_str[:i+1] if (curr[0] == '0' and len(curr) != 1) or int(curr) >= 2**31: continue if self.dfs(num_str[i+1:], path + [int(curr)], res): return True return False
-
func splitIntoFibonacci(num string) []int { n := len(num) ans := []int{} var dfs func(int) bool dfs = func(i int) bool { if i == n { return len(ans) > 2 } x := 0 for j := i; j < n; j++ { if j > i && num[i] == '0' { break } x = x*10 + int(num[j]-'0') if x > math.MaxInt32 || (len(ans) > 1 && x > ans[len(ans)-1]+ans[len(ans)-2]) { break } if len(ans) < 2 || x == ans[len(ans)-1]+ans[len(ans)-2] { ans = append(ans, x) if dfs(j + 1) { return true } ans = ans[:len(ans)-1] } } return false } dfs(0) return ans }