题目
思路
找零钱,动态规划:
dp[i] 代表金额为 i 时,硬币的最小数
dp[i] = min(dp[i - Cj]) + 1;
表示i状态从Cj来的, Cj为零钱数,要遍历m种零钱数,看哪一个可以得到最小的。自底向上。
import java.util.Scanner;
public class Main_Coins_second {
public static void main(String[] args) {
// 得到花出去的钱 m , 则找零的钱 amount = 1024 - m
// 动态规划 dp[i] = min(dp[j] - Cj) + 1
Scanner scan = new Scanner(System.in);
int m = scan.nextInt();
int amount = 1024 - m;
int[] dp = new int[amount+1];
for (int i = 0; i <= amount; i++) {
dp[i] = i;
}
int[] coins = {1, 4, 16, 64};
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.length; j++) {
if(coins[j] <= i) {
dp[i] = Math.min(dp[i - coins[j]] + 1, dp[i]);
}
}
}
System.out.println(dp[amount]);
}
}