动态规划之硬币找零

有面值为 1 2 3 的三种硬币,数量不限,拼凑成各种整额的面值,求使用最少的硬币。
思路:输入指定面额,第一层循环是面额,因为最坏的情况是使用1块钱的硬币凑够指定面额;
第二层循环,遍历面额的数组,看面额是否符合要求;

public static void main(String[] args) {

	//面额
	int[] coin = {5,3,1};
	//整数
	int money = 10;
	//保存每一次使用的面值
	int[] coinUsed = new int[money + 1];
	modCount(coin, coin.length, money, coinUsed);
}

private static void modCount(int[] coin, length, money, int[] coinUsed) {
	
	coinUsed[0] = 0;
	for (int cents= 1; cents<= money; cents++) {
		//使用最小面额的硬币时的次数
		int minCount = cents;
		
		for (int kind = 0; kind < length; coin++) {
			if (coin[kind] <= cents) {
				int temp = coinUsed[cents - coin[kind]] + 1;
				if (temp < minCount) {
					minCount = temp;	
				}
			}
		}
		//保存最小硬币数
		coinUsed[cents] = minCount;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42046342/article/details/88404445