日期:2014-05-20 浏览次数:20663 次
public class Equals1 { // 面值 int[] values= {100,50,30,20}; int[] zhangshu = {0,0,0,0};//张数 // 库存 HashMap<Integer, Integer> invoiceMap=new HashMap<Integer, Integer>(); int total = 150; public Equals1(){ invoiceMap.put(30,3); invoiceMap.put(50,3); invoiceMap.put(20,5); invoiceMap.put(100,2); } public int action(int index,int tail){ if(index>values.length - 1){ return -1; } zhangshu[index] = Math.min(tail/values[index],invoiceMap.get(values[index])); tail -= zhangshu[index]*values[index]; if(tail==0){ return 0; } else{ for(int i= 0;i <=zhangshu[index];zhangshu[index]--){ if(action(index+1,tail)==0){ return 0; } tail += values[index]; } } return tail; } public static void main(String[] args) { Equals1 a = new Equals1(); int total = 500; a.action(0,total); if(a.action(0,total)==0){ for(Integer it:a.zhangshu){ System.out.print(it+" "); } } else{ System.out.print("不能分配该数字。"); } } }
------解决方案--------------------
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.junit.Test;
public class FP {
HashMap<Integer, Long> invoiceMap = new HashMap<Integer, Long>();// 存放发票面额和库存
ArrayList<Integer> list = new ArrayList<Integer>();
public FP() {
invoiceMap.put(30, 10L);
invoiceMap.put(50, 3L);
invoiceMap.put(20, 5L);
invoiceMap.put(100, 10L);
Set<Integer> set = invoiceMap.keySet();
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
list.add(it.next());
}
Collections.sort(list);
Collections.reverse(list);
// int total = 130;
}
public HashMap<Integer, Long> invoiceMethod(
HashMap<Integer, Long> invoiceMap, int total) {
for (int i = 0; i < list.size(); i++) {
if (total >= (Integer) list.get(i)) {
int count = total / list.get(i);
// invoiceMap 的数值发生变化
invoiceMap
.put(list.get(i), invoiceMap.get(list.get(i)) - count);
// total 减少数据
total -= count * list.get(i);
}
}
return invoiceMap;
}
private void pt(Object integer) {
System.out.println(integer);
}
@Test
public void t() {
FP f = new FP();
invoiceMethod(invoiceMap, 150);
pt(invoiceMap);
}
}