public class coinChange {
//{1,3,5} //M=11
public static int coin(int[] a,int M){
int [] f=new int[M+1];
int n=a.length;//number of kinds of coins
//initialization
f[0]=0;
int i,j;
//f[1],f[2]...f[11]
for(i=1;i<=M;i++)
{
f[i]=Integer.MAX_VALUE;
//last coin a[j]
//f[i]=min{f[i-a[0]]+1...f[i-a[n-1]]+1}
for(j=0;j<n;++j)
{
if(i>=a[j] && f[i-a[j]]!=Integer.MAX_VALUE){
f[i]=Math.min(f[i-a[j]]+1,f[i]);
}
}
}
if(f[M]==Integer.MAX_VALUE){
f[M]=-1;
}
return f[M];
}
public static void main(String[] args)
{
int []a={1,3,5};
int M=11;
int coins_number=coin(a,M);
System.out.println(coins_number);
}
}
运行结果
2.C语言代码(附运行结果)
#include<stdio.h>
int coinChange(int* coins, int coinsSize, int values) {
int* dp = (int*)calloc(values + 1, sizeof(int));
int i, j;
for (i = 0; i <= values; i++)
{
dp[i] = values + 1;//初始化
}
dp[0] = 0;
for (i = 0; i <= values; i++) {
for (j = 0; j < coinsSize; j++)
{
if (i < coins[j])
continue;
dp[i] = dp[i] < dp[i - coins[j]] + 1 ? dp[i] : dp[i - coins[j]] + 1;
}
}
return (dp[values] != values + 1) ? dp[values] : -1;
}
int main(void)
{
int coins[] = { 1,3,5 };
int coinsSize = 3;
int values = 11;
int num = coinChange(coins, coinsSize, values);
printf("最少需要%d枚硬币\n", num);
return 0;
}