凑零钱
import java.util.Arrays;;
//凑零钱问题(动态规划),至少需要多少枚
//coins零钱面值,amount宗金额
//dp[i]=x表示当目标金额为i时。至少需要x枚硬币
public class Test6 {
public static int coinChange(int[] coins, int amount) {
int[] dp = new int[amount+1];
Arrays.fill(dp, amount+1);
dp[0]=0;
for(int i=0; i<dp.length; i++) {
for(int coin:coins) {
if(i-coin<0) continue;
dp[i]=Math.min(dp[i],dp[i-coin]+1);
}
}
return (dp[amount]==amount+1)?-1:dp[amount];
}
public static void main(String[] args) {
int[] coins = {1,1,1,2,2,2,5};
int a = coinChange(coins,3);
System.out.println(a);
}
}