zoukankan      html  css  js  c++  java
  • 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%的用户
  • 相关阅读:
    1641. 统计字典序元音字符串的数目
    1688. 比赛中的配对次数
    核心思路
    面试题 16.17. 连续数列
    70. 爬楼梯
    面试题 08.01. 三步问题
    剑指Offer 42. 连续子数组的最大和
    设计模式之原型模式
    代理模式之动态代理
    设计模式之禅(六大设计原则)
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14119117.html
Copyright © 2011-2022 走看看