随笔-60  评论-98  文章-0  trackbacks-0
贪心算法,可以求得近似最优解。
posted on 2006-09-25 16:03 创建更好的解决方案 阅读(550) 评论(1)  编辑 收藏 引用

评论:
# re: GOOGLE笔试题之找零钱 2007-10-12 16:20 | 创建更好的解决方案
http://blog.csdn.net/paradise80/archive/2004/12/05/205519.aspx
田东专栏修改后的C#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Implememtations
{
/// <summary>
/// Calculates the minimum count of change.
/// </summary>
public class MoneyChanger
{
/// <summary>
/// Initializes an instance of <c>MoneyChange</c> with par values.
/// </summary>
/// <param name="parValues">Par values(e.g 10, 5, 2, 1 for RMB).</param>
public MoneyChanger(int[] parValues)
{
if (parValues == null)
{
throw new ArgumentNullException("parValues");
}

this.parValues = this.FilterParValues(parValues);

if (this.parValues.Count == 0)
{
throw new ArgumentException("Invalid par values");
}
}

/// <summary>
/// Gets change with minimum count of par values.
/// </summary>
/// <param name="amount">Total amount to be changed.</param>
/// <returns>(parValue, count) pairs.</returns>
public virtual Dictionary<int, int> Change(int amount)
{
Dictionary<int, int> result = new Dictionary<int, int>(this.parValues.Count);

foreach (int par in this.parValues)
{
result.Add(par, amount / par);
amount %= par;
}

return result;
}

#region Fields

/// <summary>
/// Stores par values.
/// </summary>
private List<int> parValues;

#endregion Fields

#region Supports Methods

/// <summary>
/// Filters par values with following rules:
/// 1. All values are greater then zero.
/// 2. All have different value.
/// 3. Sorted in descending order.
/// </summary>
/// <param name="parValues">Array of par values.</param>
/// <returns>Filtered par values.</returns>
private List<int> FilterParValues(int[] parValues)
{
List<int> temp = new List<int>(parValues.Length);
List<int> list = new List<int>(parValues.Length);

// Filters positive integers.
foreach (int par in parValues)
{
if (par > 0)
{
temp.Add(par);
}
}

// Sorts values.
temp.Sort();

// Adds to list in descending order.
for (int i = temp.Count - 1; i >= 0; i--)
{
if (list.Count > 0)
{
// Ingores the duplicate value.
if (temp[i] == list[list.Count - 1])
{
continue;
}
}

list.Add(temp[i]);
}

return list;
}

#endregion Supports Methods
}
}  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理