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
| class Solution { public List<Integer> splitIntoFibonacci(String S) { List<Integer> ans = new ArrayList<>(); backtrack(S, 0, 0, 0, ans); return ans; }
private boolean backtrack(String S, int index, int sum, int prev, List<Integer> ans) { if (index == S.length()) return ans.size() >= 3; long currLong = 0; for (int i = index; i < S.length(); i++) { if (i > index && S.charAt(index) == '0') break; currLong = currLong * 10 + S.charAt(i) - '0'; if (currLong > Integer.MAX_VALUE) break; int curr = (int) currLong; if (ans.size() >= 2) { if (curr < sum) continue; if (curr > sum) break; } ans.add(curr); if (backtrack(S, i + 1, prev + curr, curr, ans)) return true; ans.remove(ans.size() - 1); } return false; } }
|