查找表是一個很好的方法。在幾毫秒內
void CalculateTable()
{
for (int i = Coins.Length-1; i >= 0; i--)
{
int coin = Coins[i];
for (int cents = 0; cents < 6400; cents++)
{
if (i == Coins.Length-1)
{
// The 1 cent coin can't be divided further
Table[i,cents] = cents;
}
else
{
// Find the count that minimizes the number of tubes.
int n = cents/coin;
int bestTubes = -1;
int bestCount = 0;
for (int count = cents/coin; count >= 0; count--)
{
int cents1 = cents - count * coin;
int tubes = (count + 63)/64;
// Use the algorithm from Tubes() above, to optimize the
// lesser coins.
for (int j = i+1; j < Coins.Length; j++)
{
int count1 = Table[j, cents1];
cents1 -= count1 * Coins[j];
tubes += (count1 + 63)/64;
}
if (bestTubes == -1 || tubes < bestTubes)
{
bestTubes = tubes;
bestCount = count;
}
}
// Store the result
Table[i,cents] = bestCount;
}
}
}
}
CalculateTable
運行,所以你不必將其存儲到磁盤的更多信息:
int[] Coins = new[] { 100, 50, 25, 10, 5, 1 };
int[,] Table = new int[6,6400];
/// Calculate the number of coins of each type that minimizes the number of
/// tubes used.
int[] Tubes(int cents)
{
int[] counts = new int[Coins.Length];
if (cents >= 6400)
{
counts[0] += (cents/6400) * 64; // number of coins in filled $1-tubes
cents %= 6400;
}
for (int i = 0; i < Coins.Length; i++)
{
int count = Table[i, cents]; // N coins in (N + 63)/64 tubes
counts[i] += count;
cents -= count * Coins[i];
}
return cents;
}
要計算表,您可以使用此。
實施例:
Tubes(3149) -> [ 31, 0, 0, 0, 0, 49]
Tubes (3150) -> [ 0, 63, 0, 0, 0, 0]
Tubes (31500) -> [315, 0, 0, 0, 0, 0]
中的數字是指硬幣的數目。 Ñ硬幣可被放入(Ñ + 63)/ 64管。
看來,一個簡單的蠻力方法應該足夠好,除非你想要處理大量的金錢? –
老實說?我對編程非常陌生,幾乎不知道從哪裏開始,我試圖想方設法修改一個貪婪的方法,曾經考慮過蠻橫的問題,但是我遇到了麻煩,即使得到了組合的數量或找到了我可以理解的例子(關於如何從金額中獲得硬幣的組合)。我剛剛在stackoverflow上找到了一個可以遵循的例子,所以我馬上就會更新。 –
25美分的例子可以在一個管中使用25個1c硬幣完成嗎? –