贪婪算法

  1. package convex;   
  2.   
  3. import java.util.Arrays;   
  4.   
  5. /**
  6. * 输入一个C,
  7. * 再输入N个不同面值的纸币
  8. * 组合成C,求出所用纸币的张数最少的张数
  9. * 比如: C=100,N=5 有5个不同的面值,1,5,20,80,90
  10. * 最后输出的结果为2
  11. *
  12. * 如果是排序的,复杂度为o(n^2),非排序的话,复杂度为o(n*logn+n^2) 采用的方法:贪婪算法
  13. *
  14. * @author B.Chen
  15. */  
  16. public class CalMoney {   
  17.   
  18.     public static int calMoney(int c, int[] array, int length) {   
  19.         int total = 0;   
  20.         if (c != 0) {   
  21.             while (c < array[length - 1]) {   
  22.                  length--;   
  23.              }   
  24.              total = c / array[length - 1]   
  25.                      + calMoney(c % array[length - 1], array, length - 1);   
  26.          }   
  27.         return total;   
  28.      }   
  29.   
  30.     public static void main(String[] args) {   
  31.         int[] a = new int[] { 5, 1, 80, 20, 90, 200, 500, 700 };   
  32.          Arrays.sort(a);   
  33.         int min = 999;   
  34.         for (int i = a.length; i > 0; i--) {   
  35.             int count = calMoney(100, a, i);   
  36.             if (min > count) {   
  37.                  min = count;   
  38.              }   
  39.          }   
  40.          System.out.println(min);   
  41.      }   
  42. }  
原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100616.html