Leetcode842.将数组拆分为斐波拉契数列

题目链接:842. 将数组拆分成斐波那契序列

思路:暴力遍历。从长度为1开始,初始化n1、n2、n3,当n1+n2!=n3时,n3长度加1,直到超出字符串长度的一半;当n1+n2==n3时,令n1=n2,n2=n3,然后获取n3的值,并重新判断呢n1+n2是不是等于n3.

代码:

class Solution {
    public List<Integer> splitIntoFibonacci(String S) {
        LinkedList<Integer> res = new LinkedList<>();
        helper(S, 0, -1, -1, res);
        return res;
    }
   //S数字字符串,start开始的位置索引,n1第一个数,n2第二个数字,res结果List
    private boolean helper(String S, int start, int n1, int n2, LinkedList<Integer> res){
        if(start > S.length()) return false;//超出长度,返回false;
        if(start == S.length()) return true;//正好满足要求,返回true
        int t;
        for(int len = 1; len <= (S.length() >> 1) && start+len<=S.length(); len++){
            if(S.charAt(start) == '0') {t = 0;len = 1;}//当前字符以‘0’开头时,len只能为1,不能改变len的值
            else {
                long tt = Long.valueOf(S.substring(start, start + len));
                if(tt > Integer.MAX_VALUE) return false;//判断数字是不是大于最大整型
                t = (int)tt;
            }
            res.offerLast(t);
            if(n1 == -1){
                if(helper(S, start+len, t, -1, res) && res.size()>2)
                    return true;
            }else if(n2 == -1){
                if(helper(S, start+len, n1, t, res) && res.size()>2)
                    return true;
            }else{
                if(n1 + n2 == t && helper(S, start+len, n2, t, res) && res.size()>2)
                    return true;
            }
            res.pollLast();
            if(t == 0) break;
        }
        return false;
    }
}
执行用时:4 ms, 在所有 Java 提交中击败了69.62%的用户
内存消耗:38.7 MB, 在所有 Java 提交中击败了59.02%的用户
原文地址:https://www.cnblogs.com/liuyongyu/p/14119117.html