某国发行n种面额的钞票,现需要找零钱给顾客,设计一个算法,用最少的钞票张数找给顾客(每种钞票都有足够的张数)
输入:有多少张不同面额的钞票、每张钞票的面额
输出:对于1-30元的每种情况,给出最少钞票张数,以及每种面额钞票各几张
package stest;
import java.util.*;
public class Test2 {
public static void main(String[] args) {
final int AIM = 30;
Scanner scan = new Scanner(System.in);
System.out.print("输入n值:");
int n = scan.nextInt();
System.out.print("依次输入钞票面额:");
int[] money = new int[n];
for(int i = 0; i < n; i++) {
money[i] = scan.nextInt();
}
Map<Integer, ArrayList<Integer>> map = dp(n,money,AIM);
System.out.println("零钱 "+"张数 "+"各面额的张数");
for(int i = 0; i <= AIM; i++) {
ArrayList<Integer> arrayList = map.get(i);
System.out.print("j=" + i + " " + arrayList.get(0));
for(int j = 1; j <= n; j++) {
System.out.print(" d[" + j + "]="+arrayList.get(j));
}
System.out.println();
}
scan.close();
}
public static Map<Integer, ArrayList<Integer>> dp(int n, int[] money, int aim) {
//保存键值对总额aim->保存每种面额张数的数组
Map<Integer, ArrayList<Integer>> map = new HashMap<>(aim+1);
//保存初始状态
map.put(0, new ArrayList<>(Collections.nCopies(n+1, 0)));
for(int i = 1; i <= aim; i++) {
for(int j = 1; j <= money.length; j++) {
if (money[j-1] <= i) {
if (!map.containsKey(i)) {
ArrayList<Integer> value = new ArrayList<>();
value.addAll(map.get(i - money[j-1]));
int count = value.get(0) + 1;
value.set(0, count);
int jCount = value.get(j) + 1;
value.set(j, jCount);
map.put(i, value);
}else{
ArrayList<Integer> pValue = new ArrayList<>();
pValue.addAll(map.get(i - money[j-1]));
int pCount = pValue.get(0) + 1;
ArrayList<Integer> nValue = new ArrayList<>();
nValue.addAll(map.get(i));
int nCount = nValue.get(0);
if (pCount < nCount) {
int jCount = pValue.get(j) + 1;
pValue.set(j, jCount);
int count = pValue.get(0) + 1;
pValue.set(0, count);
map.put(i, pValue);
}
}
}
}
}
return map;
}
}
结果截图: