LC322 零钱兑换

题目描述:

使用动态规划解决:

 方法一:自顶向下(递归备忘录)

class Solution {
    public int coinChange(int[] coins, int amount) {
            int def[]=new int[amount+1]; //备忘录数组 数组长度为amount+1 
                                         //目的是为了记录每一个目标为amount所用硬币的最优解
 return dp(coins,amount,def);
}
public int dp(int []coins,int amount,int def[]){//dp递归
//base case
    if(amount==0){
        return 0;
    }
    if(amount<0){
        return -1;
    }
    if(def[amount]!=0){//若该备忘录已记录了最优解,则直接返回,避免了子问题的冗杂
        return def[amount];
    }
   int res=Integer.MAX_VALUE;//要求最小值,所以初始化为正无穷
   for(int coin:coins){//遍历硬币数组
       int subproblem=dp(coins,amount-coin,def);//子问题的解 
       if(subproblem==-1)  continue;//无解的话直接进入下一种情况
       res=Math.min(res,1+subproblem);//为什么这里要加一,res指的是用的硬币数,
                                      //比如amount=11,就是再amount=10的最优解的情况下加一枚硬币(这里是加上了1元硬币)
   }
  def[amount]=(res==Integer.MAX_VALUE?-1:res);//判断res是否有解
   return def[amount];
}
    }

方法二:自底向上(迭代dp数组)

class Solution {
    public int coinChange(int[] coins, int amount) {//迭代
int dp[]=new int [amount+1];
for(int i=0;i<dp.length;i++){//初始化dp数组
    dp[i]=amount+1;//每个数字的元素相当于正无穷,因为最多用amount个硬币
}
dp[0]=0;//amount为0时所用硬币为0
for(int i=0;i<=amount;i++){//遍历dp数组
    for(int coin:coins){//对应所选硬币的情况
        if(i-coin<0){//相当于amount-coin 
      continue;
        }
        dp[i]=Math.min(dp[i],1+dp[i-coin]);//选择最优解
    }
}
return dp[amount]==amount+1?-1:dp[amount];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值