```
public class ChangeMoney {
public static HashMap<Integer, ArrayList<Integer>> cache= new HashMap<Integer, ArrayList<Integer>>();
public static void main(String[] args) {
int[] moneys = new int[]{1,2,5,10};
changeMoney(63,moneys);
while(true){
System.out.println("输入你想查找的找零数额:");
Scanner scan = new Scanner(System.in);
int totalMoney = scan.nextInt();
if(totalMoney == 0){
System.out.println("退出程序...");
break;
}
// printList();
System.out.println(changeMoney(totalMoney, moneys).toString());
}
}
public static ArrayList<Integer> changeMoney(int totalMoney , int[] moneys){
if(totalMoney == 0){
return new ArrayList<Integer>();
}
if(cache.get(totalMoney) != null){ // 返回已存在的缓存数据
return cache.get(totalMoney);
}
ArrayList<Integer> min = null;
ArrayList<Integer> newMin = null;
ArrayList<Integer> list = null;
int money = totalMoney;
for (int i = 0; i < moneys.length; i++) {
money = totalMoney - moneys[i];
if(money >= 0){
newMin = changeMoney(money, moneys);
}
/*
* 判断是不是最小的找零数组, 如果是就将数据添加到最小找零列表中
*/
if(money >= 0 && (min == null || newMin.size() < min.size() - 1)){
list = new ArrayList<Integer>();
list.add(moneys[i]);
list.addAll(newMin);
System.out.println("对总数 : " + totalMoney + " 进行找零");
// printList(list);
System.out.println(list.toString());
min = list;
cache.put(totalMoney, min);
}
}
return cache.get(totalMoney);
}
public static void printList(ArrayList<Integer> list){
for (Integer i : list) {
System.out.print(i + " ," );
}
System.out.println();
}
}
```