842. Split Array into Fibonacci Sequence

Problem:
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 all 0 <= 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.
Analysis:
这道题思路很简单,但是Corner case很多。
1. 如果res 的size > 2, 当前取的val比target小也符合,因为后面会加更多的数进来。一旦大了就没必要继续了
2. 如果取得数大于1位,而且从第一位是0也不符合,直接break
3. 当前val大于Integer.MAX_VALUE
Solution:

 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
class Solution {
    public List<Integer> splitIntoFibonacci(String S) {
        List<Integer> res = new ArrayList<>();
        helper(res, S);
        return res;
    }
    
    private boolean helper(List<Integer> res, String S) {
        if (res.size() > 2 && S.length() == 0) {
            return true;
        }
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(0) == '0' && i > 0)
                break;
            long val = Long.valueOf(S.substring(0, i + 1));
            int size = res.size();
            if (val > Integer.MAX_VALUE)
                break;
            if (size >= 2 && val > res.get(size - 1) + res.get(size - 2))
                break;
            if (size < 2 || val == res.get(size - 1) + res.get(size - 2)) {
                res.add((int)val);
                if (helper(res, S.substring(i + 1))) {
                    return true;
                }
                res.remove(res.size() - 1);
            }
        }
        return false;
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array