我对 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 钞票 5 欧元:0 钞票 10 欧元:1
-- 我的输入是 17 --
程序应该返回
硬币 2 欧元:1 钞票 5 欧元:1 钞票 10 欧元:1