【发布时间】:2019-07-09 13:06:24
【问题描述】:
我对 C# 很陌生,我有一个递归问题要解决。我想在这个硬币找零问题中得到尽可能少的硬币。我已经对其进行了调整,但我需要返回一个包含最小可能组合的 Change 类型的对象。
我尝试实现一种算法,但我拥有所有可能的组合。
using System;
using System.Collections.Generic;
using System.Linq;
// Do not modify change
class Change
{
public long coin2 = 0;
public long bill5 = 0;
public long bill10 = 0;
}
class Solution
{
// Do not modify method signature
public static Change OptimalChange(long s)
{
Change _change = new Change();
//To implement here
return _change;
}
public static int GetCombinations(int total, int index, int[] list, List<int> cur)
{
if (total == 0)
{
foreach (var i in cur)
{
Console.Write(i + " ");
}
Console.WriteLine();
return 1;
}
if (index == list.Length)
{
return 0;
}
int ret = 0;
for (; total >= 0; total -= list[index])
{
ret += GetCombinations(total, index + 1, list, cur);
cur.Add(list[index]);
}
for (int i = 0; i < cur.Count(); i++)
{
while (cur.Count > i && cur[i] == list[index])
{
cur.RemoveAt(i);
}
}
return ret;
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello Change");
int s = 41;
/*Change m = Solution.OptimalChange(s);
Console.WriteLine("Coins(s) 2euros :" + m.coin2);
Console.WriteLine("Bill(s) 5euors :" + m.bill5);
Console.WriteLine("Bill(s) 10euors :" + m.bill10);
long result = m.coin2*2 + m.bill5*5 + m.bill10*10;
Console.WriteLine("\nChange given =", + result);*/
Solution sol = new Solution();
int[] l = {
2,
5,
10
};
Solution.GetCombinations(s, 0, l, new List<int>());
}
}
预期结果
示例:可用的硬币是 {2,5,10}
-- 我的输入是 12--
程序应该返回
硬币 2 欧元:1 账单 5euors : 0 账单 10euors : 1
-- 我的输入是 17--
程序应该返回
硬币 2 欧元:1 账单 5euors : 1 账单 10euors : 1
【问题讨论】:
-
是否需要在(学校)作业中使用递归?因为我不会为此使用递归。当应该使用相同的标准时使用递归。在这种情况下,您只想尝试拟合最大值并使用模来检查较低的值。
-
不一定
-
这是这个问题的一个奇怪的版本,因为你不说如果没有解决方案怎么办,1和3就是这样。
-
一旦你计算出价值 2、5 和 10 的硬币,尝试价值 1、7 和 15 的硬币。对于 21 的输入,它应该是三个七,而不是十五和六个。
-
问题标记为“动态规划”;你能解释一下你使用的是什么动态编程技术吗?
标签: c# dynamic-programming coin-change