842. 将数组拆分成斐波那契序列
给定一个数字字符串 S,比如 S = "123456579",我们可以将它分成斐波那契式的序列 [123, 456, 579]。
形式上,斐波那契式序列是一个非负整数列表 F,且满足:
0 <= F[i] <= 2^31 - 1,(也就是说,每个整数都符合 32 位有符号整数类型);
F.length >= 3;
对于所有的0 <= i < F.length - 2,都有 F[i] + F[i+1] = F[i+2] 成立。
另外,请注意,将字符串拆分成小块时,每个块的数字一定不要以零开头,除非这个块是数字 0 本身。
返回从 S 拆分出来的任意一组斐波那契式的序列块,如果不能拆分则返回 []。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-array-into-fibonacci-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
迭代
import java.util.*;
class Solution {
public List<Integer> splitIntoFibonacci(String num) {
if (num == null || num.length() == 0) {
return Collections.emptyList();
}
long first = 0;
for (int i = 0; i < num.length() && (i == 0 || first != 0); ++i) {
first = first * 10 + num.charAt(i) - '0';
if (first > Integer.MAX_VALUE) {
break;
}
long second = 0;
for (int j = i + 1; j < num.length() && (j == i + 1 || second != 0); ++j) {
second = second * 10 + num.charAt(j) - '0';
if (second > Integer.MAX_VALUE) {
break;
}
List<Integer> ret = new ArrayList<>();
ret.add((int) first);
ret.add((int) second);
boolean init = true;
long c = 0;
long a = first, b = second;
for (int k = j + 1; k < num.length() && (init || c != 0); ++k) {
c = c * 10 + num.charAt(k) - '0';
if (c > Integer.MAX_VALUE || c > a + b) {
break;
}
if (a + b == c) {
ret.add((int) c);
a = b;
b = c;
c = 0;
init = true;
if (k == num.length() - 1) {
return ret;
}
} else {
init = false;
}
}
}
}
return Collections.emptyList();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
new Solution().splitIntoFibonacci(in.next()).forEach(System.out::println);
}
}
}
递归
import java.util.LinkedList;
import java.util.List;
class Solution {
private LinkedList<Integer> ret = new LinkedList<>();
public List<Integer> splitIntoFibonacci(String S) {
backtracing(S, 0);
return ret;
}
public boolean backtracing(String S, int start) {
// 1. 终止条件 :start == len(res)内元素大于2个,就不需要继续尝试拆分了
if (start == S.length() && ret.size() > 2) {
return true;
}
// 2. 递归过程 : 从start 往后拆分
long num = 0;
for (int i = start; i < S.length() && (i == start || num != 0); i++) {
num = num * 10 + S.charAt(i) - '0';
if (num > Integer.MAX_VALUE) {
return false;
}
if (isFibonacciSequence((int) num)) {
ret.offerLast((int) num);
if (backtracing(S, i + 1)) {
return true;
}
ret.pollLast();
}
}
return false;
}
// 判断是否能组成斐波那契数列
public boolean isFibonacciSequence(Integer num) {
if (ret.size() < 2) {
return true;
}
Integer pre1 = ret.pollLast();
Integer pre2 = ret.pollLast();
ret.offerLast(pre2);
ret.offerLast(pre1);
return pre1 + pre2 == num;
}
public static void main(String[] args) {
new Solution().splitIntoFibonacci("123456579").forEach(System.out::println);
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号