南大高级算法作业之备考题——硬币最小数量

题解:典型的dp问题,虽然题意是要用贪心,用一个一维数组来存放下标对应的钱最少需要多少枚硬币即可。 

import java.util.*;
public class Main {
    public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);
		int e_num = scan.nextInt();//测试数
		while(e_num>0){
			int type = scan.nextInt();//the type of coins
			int amount = scan.nextInt(); 
			int[] money = new int[type];//store demonination
			for(int i=0;i<type;i++){	
				money[i] = scan.nextInt();
			}
			int[] dp = new int[amount+1];
			Arrays.fill(dp,Integer.MAX_VALUE);
			dp[0] = 0;
			for(int i=1;i<amount+1;i++){
				int min = Integer.MAX_VALUE;
				for(int j=0;j<type;j++){
					if(i-money[j]>=0 && dp[i-money[j]]!=Integer.MAX_VALUE){
						if(min > dp[i-money[j]]+1){
							min = dp[i-money[j]]+1;	
						}
					}
				}
				dp[i] = min;	
			}
			if(dp[amount] == Integer.MAX_VALUE){
				System.out.println(-1);
			}else{
				System.out.println(dp[amount]);	
			}
			e_num --;
		}
    }
}
发布了36 篇原创文章 · 获赞 2 · 访问量 1976

猜你喜欢

转载自blog.csdn.net/fumonster/article/details/103292048