题目描述:
使用动态规划解决:
方法一:自顶向下(递归备忘录)
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];
}
}