C#货币兑换算法
我需要确定所有可能的钞票组合的给定输入C#货币兑换算法,c#,C#,我需要确定所有可能的钞票组合的给定输入 int[] currency = new int[] { 5, 10, 20, 50, 100, 200, 500 }; int total = 20; // result is { {5,5,5,5} {5,5,10} {10,10} {20} } int[][] result = GetCombinations(total, 0, currency); // should return the 4 combinations 这是我到目前为止所做的尝
int[] currency = new int[] { 5, 10, 20, 50, 100, 200, 500 };
int total = 20; // result is { {5,5,5,5} {5,5,10} {10,10} {20} }
int[][] result = GetCombinations(total, 0, currency); // should return the 4 combinations
这是我到目前为止所做的尝试
public static int GetCombinations(int total, int index, int[] list)
{
total = total - list[index];
if (total < 0)
{
return 0;
}
else if (total == 0)
{
return 1;
}
else
{
return 1 + GetCombinations(total, index + 1, list);
}
}
公共静态int-getcombines(int-total、int-index、int[]列表)
{
总计=总计-列表[索引];
如果(总数<0)
{
返回0;
}
否则如果(总计==0)
{
返回1;
}
其他的
{
返回1+GetCombinations(总计、索引+1、列表);
}
}
悬赏问题:
我需要一种方法来获得所有的组合,而不仅仅是计数。您只需要计算{5},{5,10}
您正在计算“如果成本较高,可以使用多少不同的硬币”这是一个今天多次出现的问题:请谷歌”硬币更换问题“因为这是一个常见的算法问题:你得到2,因为如果你把它写下来,你会看到递归的输入是
15,1
,然后5,2
,这意味着5-20小于0。这些代码都不是为了返回组合而设计的,尽管在这个递归函数中应该有一个循环,因此在循环中调用getcomposition
应该覆盖所有可能的情况,包括下一个注释与当前注释相同的情况。另外,调用getcombines
也应该更改total
参数。这是一个动态规划问题!附带问题-此方法是否也可用于输出所有组合?否,仅用于多种方式。如果要输出所有组合,请使用回溯。我改进了我的代码,它还计算了所有组合。我编辑了此代码并删除了静态列表cur。
public static int GetCombinations(int total, int index, int[] list)
{
if (total == 0)
{
return 1;
}
if(index == list.Length) {
return 0;
}
int ret = 0;
for(; total >= 0; total -= list[index])
{
ret += GetCombinations(total, index + 1, list);
}
return ret;
}
using System;
using System.Collections.Generic;
class Program {
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 static void Main() {
int[] l = { 5, 10, 20, 50, 100, 200, 500 };
GetCombinations(20, 0, l, new List<int>());
}
}