找零钱

来源:互联网 发布:百度推广账户换域名 编辑:程序博客网 时间:2024/06/11 22:37

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

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

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

样例输入:

140
样例输出:

13
实现代码:

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