-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacciArraySplitter.java
72 lines (57 loc) · 2.03 KB
/
FibonacciArraySplitter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package org.sean.backtracking;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/***
* 842. Split Array into Fibonacci Sequence
*/
public class FibonacciArraySplitter {
public List<Integer> splitIntoFibonacci(String num) {
if (num.length() < 3)
return Collections.emptyList();
out.clear();
found = false;
search(num, 0, new LinkedList<>());
return out;
}
private List<Integer> out = new ArrayList<>();
private boolean found;
private void search(String num, int pos, LinkedList<String> fibs) {
if (found) return;
int len = num.length();
for (int i = 1; i < len - pos + 1; i++) {
if (pos + i > len)
break;
String sub = num.substring(pos, pos + i);
if (sub.startsWith("0") && sub.length() > 1)
break;
// stops when it's out of the Integer range
if (Long.parseLong(sub) > Integer.MAX_VALUE) {
break;
}
if (fibs.size() < 2) {
fibs.add(sub);
search(num, pos + i, fibs);
fibs.removeLast();
} else {
int last = Integer.parseInt(fibs.getLast());
int preLast = Integer.parseInt(fibs.get(fibs.size() - 2));
String next = String.valueOf(last + preLast);
if (sub.equals(next)) {
fibs.add(sub);
if (pos + i >= len) {
found = true;
out = fibs.stream().map(Integer::parseInt).collect(Collectors.toList());
return;
}
search(num, pos + i, fibs);
fibs.removeLast();
} else if (sub.length() >= next.length()) { // prune the branch as the next number can't be formed
return;
}
}
}
}
}