找零钱

描述: 我们知道人民币有1、2、5、10、20、50、100这几种面值。现在给你n(1≤n≤250)元,让你计算换成用上面这些面额表示且总数不超过100张,共有几种。比如4元,能用4张1元、2张1元和1张2元、2张2元,三种表示方法。

输入:输入有多组,每组一行,为一个整合n。输入以0结束。

输出:输出该面额有几种表示方法。

样例输入:

1
4
0
样例输出:

1
3
实现代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 我们知道人民币有1、2、5、10、20、50、100这几种面值。
 * 现在给你n(1≤n≤250)元,让你计算换成用上面这些面额表
 * 示且总数不超过100张,共有几种。比如4元,能用4张1元、
 * 2张1元和1张2元、2张2元,三种表示方法。
 */
public class GetChanges {
	static int[] Items;
	static long[][] Matrix;

	public static void main(String[] args) {
		Items = new int[] { 100, 50, 20, 10, 5, 2, 1 };
		List<Integer> moneys = new ArrayList<Integer>();
		List<Long> counts = new ArrayList<Long>();
		String text = input();
		int n = Integer.valueOf(text);
		do {
			Matrix = new long[n + 1][Items.length];
			moneys.add(n);
			counts.add(GetCount(0, n));
			text = input();
			n = Integer.valueOf(text);
		} while (n != 0);
		int size = counts.size();
		for (int i = 0; i < size - 1; i++) {
			System.out.println(counts.get(i));
		}
		System.out.print(counts.get(size - 1));
	}

	private static String input() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String text = "";
		try {
			text = br.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return text;
	}

	static long GetCount(int currentIndex, int remain) {
		// 如果金额小于0,返回0种
		if (remain < 0)
			return 0;

		// 如果金额=0,或算到1元了则正好可以被兑换
		if (remain == 0 || currentIndex == Items.length - 1)
			return 1;

		if (Matrix[remain][currentIndex] == 0)
			Matrix[remain][currentIndex] = GetCount(currentIndex + 1, remain)
					+ GetCount(currentIndex, remain - Items[currentIndex]);

		return Matrix[remain][currentIndex];
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值