## 找零钱的两种方法

2011-03-06 20:31 by Anders Cui, ... 阅读, ... 评论, 收藏, 编辑

public static int[] MakeChange(int money, int[] changes){    int[] result = new int[changes.Length];    for (int i = 0; i < changes.Length; i++)    {        result[i] = money / changes[i];        money = money % changes[i];        if (money == 0) { break; }    }    return result;}

1）如果n = 1，则用1个1元来找零，这就是最优解；

2）如果n > 1，则对于每个可能的值i，分别找出i元和n-i元来。

public static void MakeChangeDynamically(int money, int[] changes, int[] changesUsed, int[] lastChange){    changesUsed[0] = 0;    lastChange[0] = 1;    for (int dollars = 1; dollars <= money; dollars++)    {        // 至少可以全部使用1元来找零        int minChangeCount = dollars;        int newChange = 1;        for (int j = 0; j < changes.Length; j++)        {            if (changes[j] > dollars)            {                continue; // 不能使用该数额来找零            }            // 如果使用这个数额来找所需要的数目更小            if (changesUsed[dollars - changes[j]] + 1 < minChangeCount)            {                minChangeCount = changesUsed[dollars - changes[j]] + 1;                newChange = changes[j];            }        }        changesUsed[dollars] = minChangeCount;        lastChange[dollars] = newChange;    }}

http://en.wikipedia.org/wiki/Greedy_algorithm
http://en.wikipedia.org/wiki/Optimization_problem
http://en.wikipedia.org/wiki/Dynamic_programming