贪心算法解决钱币找零问题
发布时间:2020-12-20 10:57:33 所属栏目:Python 来源:网络整理
导读:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Coin{ class Program { static void Main( string [] args) { int [] value = new int [] { 1 , 2 , 5 , 10 , 20 , 50 ,
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Coin { class Program { static void Main(string[] args) { int[] value = new int[] { 1,2,5,10,20,50,100 }; int[] count = new int[] { 3,0,1,3,5 }; int[] result = new int[count.Length+1];//将每个面额的货币使用数量记录下来,最后一个记录找零的情况 CoinMoneny(600,value,count,result);//600块进行找零 foreach (var item in result)//将找零的情况进行输出 { Console.WriteLine(item); } Console.ReadKey(); } /// <summary> /// 对货币进行找零 /// </summary> /// <param name="money"></param> /// <param name="value"></param> /// <param name="count"></param> /// <param name="result"></param> public static void CoinMoneny(int money,int[] value,int[] count,int[] result) { if (money <= 0)//先判断是否有找零的必要 { return; } int temp = value.Length - 1;//先从最大面额进行找零 while(true) { if(money>value[temp]*count[temp])//最大面额总数小于找零数 { result[temp] = count[temp];//将最大面额所有的数量全部记录到数组中 money -= value[temp] * count[temp];//将最大面额使用完后的找零钱数 } else//最大面额总数大于找零数 { result[temp] = money / value[temp];//按照实际情况把找零的数量记录 money -= result[temp] * value[temp];//还剩下的找零数 } temp = temp - 1;//检测下一个面额的钱币 if(temp<0||money<=0)//终止查找 { break; } } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |