首页 > 其他分享 >leetcode-509-easy

leetcode-509-easy

时间:2022-10-24 18:02:07浏览次数:71  
标签:int Explanation result easy 509 Output n2 Input leetcode

Fibonacci Number

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Constraints:

0 <= n <= 30

思路一: 动态规划

public int fib(int n) {
    if (n < 2) return n;
    
    int n1 = 0;
    int n2 = 1;
    int result = 0;
    for (int i = 2; i < n; i++) {
        result = n2 + n1;
        n1 = n2;
        n2 = result;
    }

    return result;
}

标签:int,Explanation,result,easy,509,Output,n2,Input,leetcode
From: https://www.cnblogs.com/iyiluo/p/16822290.html

相关文章

  • leetcode-383-easy
    RansomNoteGiventwostringsransomNoteandmagazine,returntrueifransomNotecanbeconstructedbyusingthelettersfrommagazineandfalseotherwise.Ea......
  • leetcode-541-easy
    ReverseStringIIGivenastringsandanintegerk,reversethefirstkcharactersforevery2kcharacterscountingfromthestartofthestring.Iftherear......
  • leetcode-504-easy
    Base7Givenanintegernum,returnastringofitsbase7representation.Example1:Input:num=100Output:"202"Example2:Input:num=-7Output:"-10......
  • 开发那些事儿:EasyCVR时间组件报错,是什么原因?
    EasyCVR具备较强的视频能力,可支持海量设备接入、汇聚与管理、视频监控、视频录像、云存储、回放与检索、智能告警、平台级联等功能。平台可支持多协议接入,包括:国标GB/T2818......
  • leetcode 2448
    首先需要这个结论.  而这里a_iai​为任意正整数,我们便可以直接将其**拆为**a_iai​个系数为11的绝对值表达式的和。接下来只需要考虑全体的中位数即可(采......
  • D1. Balance (Easy version)
    D1.Balance(Easyversion)Thisistheeasyversionoftheproblem.Theonlydifferenceisthatinthisversionthereareno"remove"queries.Initiallyyouha......
  • easyExcel 填充模板生成新的excel
    POM<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.1</version></dependency> 主要代......
  • leetcode 32. 最长有效括号 js实现
    https://leetcode.cn/problems/longest-valid-parentheses/给你一个只包含'(' 和')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。示例1:输入:s="(()"输出......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:合并两个有序链表
    题目:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例1:输入:l1=[1,2,4],l2=[1,3,4]输出:[1,1,2,3,4,4]示例2:......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:最接近的三数之和
    题目:给你一个长度为n的整数数组 nums 和一个目标值 target。请你从nums中选出三个整数,使它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在恰好一......