我需要编写一个程序,显示所有可能的变化组合,给出一系列面额[1,2,5,10,20,50,100,200] // 1 = 1分
从= 300
进行更改的值我的代码基于此网站http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
的解决方案#include<stdio.h>
int count( int S[], int m, int n )
{
int i, j, x, y;
// We need n+1 rows as the table is consturcted in bottom up manner using
// the base case 0 value case (n = 0)
int table[n+1][m];
// Fill the enteries for 0 value case (n = 0)
for (i=0; i<m; i++)
table[0][i] = 1;
// Fill rest of the table enteries in bottom up manner
for (i = 1; i < n+1; i++)
{
for (j = 0; j < m; j++)
{
// Count of solutions including S[j]
x = (i-S[j] >= 0)? table[i - S[j]][j]: 0;
// Count of solutions excluding S[j]
y = (j >= 1)? table[i][j-1]: 0;
// total count
table[i][j] = x + y;
}
}
return table[n][m-1];
}
// Driver program to test above function
int main()
{
int arr[] = {1, 2, 5, 10, 20, 50, 100, 200}; //coins array
int m = sizeof(arr)/sizeof(arr[0]);
int n = 300; //value to make change from
printf(" %d ", count(arr, m, n));
return 0;
}
程序运行正常。它显示了所有可能组合的数量,但我需要它更高级。我需要它的工作方式是以下列方式显示结果:
1分:n种可能的组合。
2美分:
5美分:
依旧......
如何修改代码来实现这一目标?
答案 0 :(得分:0)
贪婪算法方法
在int数组中有这样的面额说,int den [] = [1,2,5,10,20,50,100,200]
迭代这个数组
对于每次迭代,请执行以下操作
获取面额数组中的元素
将要分配的更改除以面额数组编号
中的元素如果更改分配的数字完全可以被面额数组中的数字整除,那么您将完成该数字的更改。
如果数字不是完全可分的,那么检查余数并用其他数字进行相同的迭代
一旦获得等于更改数的值
,退出内部迭代对我们的面额数组中可用的下一个面额执行相同的操作。
Explained with example
den = [1 , 2, 5, 10, 20, 50, 100, 200]
Change to be alloted : 270, let take this as x
and y be the temporary variable
Change map z[coin denomination, count of coins]
int y, z[];
First iteration :
den = 1
x = 270
y = 270/1;
if x is equal to y*den
then z[den, y] // z[1, 270]
Iteration completed
Second Iteration:
den = 2
x = 270
y = 270/2;
if x is equal to y*den
then z[den , y] // [2, 135]
Iteration completed
Lets take a odd number
x = 217 and den = 20
y= 217/20;
now x is not equal to y*den
then update z[den, y] // [20, 10]
find new x = x - den*y = 17
x=17 and identify the next change value by greedy it would be 10
den = 10
y = 17/10
now x is not equal to y*den
then update z[den, y] // [10, 1]
find new x = x - den*y = 7
then do the same and your map would be having following entries
[20, 10]
[10, 1]
[5, 1]
[2, 1]