动态规划系列(1) leetcode java

news/2024/7/8 5:43:07

第一题:

斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:

 核心思想: F(n)=F(n−1)+F(n−2)

class Solution {
    public int fib(int n) {
        int f0 = 0;
        int f1 = 1;
        int tmp;
        if(n<=1){
            return n;
        }
        while(n>1){
            tmp = f1;
            f1 +=f0;
            f0 = tmp;
            n--;
        }
        return f1;
    }
}

 

第二题:

第 N 个泰波那契数

泰波那契序列 Tn 定义如下: 

T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

 

class Solution {
    public int tribonacci(int n) {
        int t0 = 0;
        int t1 = 1;
        int t2 = 1;
        int tmp = 0;
        if(n<2){
            return n;
        }
        if(n==2){
            return 1;
        }
        while(n>2){
            tmp = t2;
            t2+=t0+t1;
            t0=t1;
            t1=tmp;
            n--;
        }
        return t2;
    }
}

 


http://www.niftyadmin.cn/n/3651721.html

相关文章

FEW MORE CUPS OF COFFEE铪铪

AUG.2,2005FEW MORE CUPS OF COFFEEby Kakuji FunegataDo I have to remind you,Whom I owe cups of coffee to ?I am and will be forever in your debtUntil I do you the favor at last.Is it alright that you I inviteTo have some coffee at any time you like ?To the…

动态规划系列(2) leetcode java

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; class Solution {public int climbStairs(int n) {int s 0;int e 1;int tmp 0;while(n-->0){tmp e;es;s tmp;}return e;} } 第二题: 给你…

买卖股票的最佳时机 leetcode java篇

给定一个数组 prices &#xff0c;它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票&#xff0c;并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。…

动态规划系列(3) leetcode java篇

第一题: 打家劫舍 你是一个专业的小偷&#xff0c;计划偷窃沿街的房屋。每间房内都藏有一定的现金&#xff0c;影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统&#xff0c;如果两间相邻的房屋在同一晚上被小偷闯入&#xff0c;系统会自动报警。 给定一个代表…

动态规划系列(4) leetcode Java篇

第一题: 跳跃游戏 给定一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标。 class Solution {public boolean canJump(int[] num) {int len num.length;if(len1){re…

What the heck is H5N1?

What the heck is "H5N1"?PROPOSAL:H5N1 Heal Five, Not OneEXPLANATION:1. Heal the patients.2. Heal each broken heart.3. Heal every lost minds & souls.4. Heal the society.5. Heal the world.

动态规划系列(5) leetcode java 篇

第一题: 最大子数组和 给你一个整数数组 nums &#xff0c;请你找出一个具有最大和的连续子数组&#xff08;子数组最少包含一个元素&#xff09;&#xff0c;返回其最大和。 子数组 是数组中的一个连续部分。 class Solution {public int maxSubArray(int[] ns) {int max …

游戏交互设计顶尖大师Chris Crawford最新力作《Chris Crawford on Interactive Storytelling》

游戏交互设计顶尖大师 Chris Crawford 继 2003 年的杰作 Chris Crawford on Game Design &#xff08; http://www.informit.com/title/0131460994 &#xff09;之后&#xff0c;于 2004 年底再出新作&#xff0c;全面展现游戏交互设计之精髓&#xff01;Chris Crawford on Int…