● 70. 爬楼梯 (进阶)
class Solution {public int climbStairs(int n) {int[] dp = new int[n+1];//设置背包容量:n个int m =2;//有两个物品,注意这是一个完全背包问题dp[0] = 1;//initialize for(int i = 1;i<=n;i++){//遍历背包for(int j = 1;j<=m;j++){//遍历物品if(i >= j) dp[i] += dp[i-j];//走了 j 步,就还剩下i-j//而dp[i]是指到达i层的总方法数}}return dp[n];} }
● 322. 零钱兑换
class Solution {public int coinChange(int[] coins, int amount) {// 注意题目中说的是最少硬币书,与排列和组合都没有关系,所以for循环顺序随便,因为我们始终要遍历物品和背包int max = Integer.MAX_VALUE;int[] dp = new int[amount+1];dp[0] = 0;for(int i =1;i<=amount;i++){dp[i] = max;}for(int i = 0;i<coins.length;i++){for(int j = coins[i];j<=amount;j++){//还是对每个硬币进行遍历,只是根据硬币来看的//肯定是j-coins[i],不是j本身哈,这样保证了从0开始if(dp[j - coins[i]]!=max){dp[j] = Math.min(dp[j],dp[j-coins[i]]+1);}} } return dp[amount]==max?-1:dp[amount];}}
● 279.完全平方数
class Solution {public int numSquares(int n) {int[] dp = new int[n+1];//背包容量int max = Integer.MAX_VALUE;for(int i =1;i<=n;i++){dp[i] = max;}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];} }