类似于找一定数目的钱,使用最少的钱数达到效果,凑钱问题
/************************************
* author:lijia
* date:2016-04-20
* description:通过计算获得一个使用最少
* 量充值卡满足充值额度的方案
* **********************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CountMoney
{
class Counter
{
/// <summary>
/// 总钱数
/// </summary>
private int money;
/// <summary>
/// 面额选择
/// </summary>
private int[] choice;
/// <summary>
/// 选择的面额
/// </summary>
private List<int> needType = new List<int>();
/// <summary>
/// 各面额需要数目的结果
/// </summary>
public Dictionary<int, int> dicResult = new Dictionary<int, int>();
/// <summary>
/// 构造函数,初始化参数
/// </summary>
/// <param name="money"></param>
/// <param name="choice"></param>
public Counter(string money, int[] choice)
{
this.money = int.Parse(money);
this.choice = choice.ToArray().OrderBy(p => p).Reverse().ToArray();
}
/// <summary>
/// 计算结果
/// </summary>
public void CountResult()
{
if (this.choice.Length > 0)
{
HandleNeedType(money);
foreach (int i in needType)
{
if(i != 0)
{
int num = money / i;
money = money % i;
dicResult.Add(i, num);
//result += string.Format("面额{0}需要数目为{1} ",i,num);
}
}
}
}
/// <summary>
/// 需要面额类型
/// </summary>
/// <param name="remain">剩余金额</param>
/// <returns>面额类型</returns>
private int GetNeedType(int remain)
{
foreach (var i in choice)
{
if (remain >= i)
{
return i;
}
}
return 0;
}
/// <summary>
/// 通过计算得到需要的面额种类,添加到list中
/// </summary>
/// <param name="remainMoney">剩余金额</param>
private void HandleNeedType(int remainMoney)
{
var need = GetNeedType(remainMoney);
if (need != 0)
{
needType.Add(need);
var remain = remainMoney % need;
if (remain > 0)
{
HandleNeedType(remain);
}
}
else
{
needType.Add(0);//如果没有最小的可用面额,添加0作为标记
}
}
}
}