力扣labuladong一刷day59天动态规划

力扣labuladong一刷day59天动态规划

一、509. 斐波那契数

题目链接:https://leetcode.cn/problems/fibonacci-number/description/
思路:这是非常典型的一道题,下面是优化过的代码,a,b就是dp数组,因为每计算一个值,需要前两个值,这个a,b就是用来记录前两个值,避免重复计算,递推公式便是f(n) = f(n-1)+f(n-2)。

class Solution {
   
    public int fib(int n) {
   
        if (n < 2) return n;
        int a = 0, b = 1, c = 0;
        for (int i = 2; i <= n; i++) {
   
            c = a + b;
            a = b;
            b = c;
        }
        return b;
    }
}

二、322. 零钱兑换

题目链接:https://leetcode.cn/problems/coin-change/description/
思路:本题是一个典型完全背包问题,物品数量无限,故物品在外,背包在内,均正序,背包正序用来满足物品无限。
定义dp数组,dp[j]表示要填满容量为j的背包所需要的最少物品数量。
递推公式为dp[j] = min(dp[j-coins[i]] + 1, dp[j]),求最少物品数量,有两种选择,要么是放入当前物品,要么是不放入当前物品。放入的话,自然就是刚好少于当前物品值的容积所对应的物品数量加1,不放入的话,直接使用dp[jj]的值,该dp[j]可能由之前的物品所填满,也有可能还没填。

class Solution {
   
   public int coinChange(int[] coins, int amount) {
   
        int[] dp = new int[amount+1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < coins.length; i++) {
   
            for (int j = coins[i]; j < dp.length; j++) {
   
                if (dp[j - coins[i]] != Integer.MAX_VALUE) {
   
                    dp[j] = Math.min(dp[j-coins[i]] + 1, dp[j]);
                }
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }
}

相关推荐

  1. labuladongday59动态规划

    2024-01-12 15:48:05       27 阅读
  2. labuladongday71动态规划5题

    2024-01-12 15:48:05       30 阅读
  3. labuladongday52LRU算法

    2024-01-12 15:48:05       39 阅读
  4. labuladongday53LFU 算法

    2024-01-12 15:48:05       44 阅读
  5. labuladongday35

    2024-01-12 15:48:05       28 阅读
  6. labuladongday34

    2024-01-12 15:48:05       41 阅读
  7. labuladongday36

    2024-01-12 15:48:05       46 阅读
  8. labuladongday51单调栈应用

    2024-01-12 15:48:05       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-12 15:48:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-12 15:48:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-12 15:48:05       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-12 15:48:05       20 阅读

热门阅读

  1. SpringSecurity入门demo(四)授权

    2024-01-12 15:48:05       38 阅读
  2. AttributeError: ‘str‘ object has no attribute ‘spilt‘

    2024-01-12 15:48:05       27 阅读
  3. 实名核验、企业工商、生活常用等API分享

    2024-01-12 15:48:05       32 阅读
  4. 代码随想录 字符串

    2024-01-12 15:48:05       41 阅读
  5. v-model 的原理

    2024-01-12 15:48:05       36 阅读
  6. Shell编程--grep、egrep

    2024-01-12 15:48:05       25 阅读