今天是第四十五天,继续动态规划
class Solution { public int climbStairs(int n) { int[] dp = new int[n+1]; dp[0] = 1; for(int i = 0; i<=n; i++){ for(int j = 1; j<= 2; j++){ int temp = i - j; if(temp < 0){ continue; } dp[i] += dp[temp]; } } return dp[n]; } }
可以转化成完全背包问题,外圈loop是背包,里面的物品
class Solution { public int coinChange(int[] coins, int amount) { int max = Integer.MAX_VALUE; int[] dp = new int[amount + 1]; for (int j = 0; j < dp.length; j++) { dp[j] = max; } dp[0] = 0; for (int i = 0; i < coins.length; i++) { for (int j = coins[i]; j <= amount; j++) { if (dp[j - coins[i]] != max) { dp[j] = Math.min(dp[j], dp[j - coins[i]] + 1); } } } return dp[amount] == max ? -1 : dp[amount]; } }
也是一道完全背包问题,但此题不受硬币顺序影响,因此内外两层for loop无论先后背包物品都是可以的
class Solution { public int numSquares(int n) { int max = Integer.MAX_VALUE; int[] dp = new int[n + 1]; for (int j = 0; j <= n; j++) { dp[j] = max; } dp[0] = 0; for (int i = 1; i * i <= n; i++) { for (int j = i * i; j <= n; j++) { if (dp[j - i * i] != max) { dp[j] = Math.min(dp[j], dp[j - i * i] + 1); } } } return dp[n]; } }
先物品再背包
今天是完全背包,明天继续!
标签:四十五天,背包,int,代码,coins,随想录,new,dp From: https://www.cnblogs.com/catSoda/p/16927651.html