贪心算法

假设你开了间小店,钱柜里的货币只有25分、10分、5分和1分四种硬币,如果你是售货员且要找给客户41分钱的硬币,如何安排才能找给客人的钱既正确且硬币的个数又最少?

 
 

using System;

 
 

namespace ConsoleApplication2

{

class
Program

{

static
void Main(string[] args)

{

int total = 46;

int[] coin = {25,10,5,1};

int[] count = new
int[4] { 0, 0, 0, 0 };

while(total>=coin[0])

{

count[0] = count[0] + 1;

total = total – coin[0];

}

while (total >= coin[1])

{

count[1] = count[1] + 1;

total = total – coin[1];

}

while (total >= coin[2])

{

count[2] = count[2] + 1;

total = total – coin[2];

}

while (total >= coin[3])

{

count[3] = count[3] + 1;

total = total – coin[3];

}

Console.WriteLine(方案如下:);

for(int i=0;i<count.Length;i++)

{

Console.WriteLine(“{0}分硬币:{1},coin[i],count[i]);

}

}

}

}

 
 

缺点:由于考虑的只是当前的最优解,而没有从整体考虑,获得的最终解不一定是最优解,只是近似解而已。

 
 

对于人生有时候也是如此,活在当下有时候能获得最好的结果。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注