给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。
计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。
你可以认为每种硬币的数量是无限的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-change
using System;
namespace 面额对应最少张钱币_动态规划_
{
class Program
{
static int Myfun(int[] Coins,int amounts)
{
int[] temp = new int[amounts + 1];
Array.Fill(temp, -1);
temp[0] = 0;
for (int i = 1; i < temp.Length; i++)
{
for (int j = 0; j < Coins.Length; j++)
{
if (Coins[j]<=i && temp[i - Coins[j]] != -1)
{
if (temp[i] == -1 || temp[i] > temp[i - Coins[j]] + 1)
temp[i] = temp[i - Coins[j]] + 1;
}
}
}
return temp[amounts];
}
static void Main(string[] args)
{
int[] Coins = Array.ConvertAll<string, int>(Console.ReadLine().Split(" "), int.Parse);
int amounts = int.Parse(Console.ReadLine());
int res = Myfun(Coins, amounts);
Console.WriteLine(res);
}
}
}
要点说明
- 未知金额X对应的硬币数:可以根据枚举所有的面额Y,则硬币数F(X)=F(X-Y)+1
此处的1代表枚举的面额的数量。Y代表枚举的金额。 - 要求F(n)最少硬币数,则需要知道F(n-Y1),F(n-Y2),F(n-Y3)…的最少硬币数
函数说明
public static void Fill<T>(T[] array, T value);
public static void Fill<T>(T[] array, T value, int startIndex, int count);
单一数值填充数组