【发布时间】:2016-02-03 18:17:59
【问题描述】:
我需要编写一个程序,在给定面额数组 [1 , 2, 5, 10, 20, 50, 100, 200] // 1 = 1 cent
的情况下显示所有可能的变化组合从 = 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 美分:
等等……
如何修改代码来实现这一点?
【问题讨论】:
-
当你说:1 美分:n 种可能的组合你的意思是有多少组合使用 1 美分硬币?如果是这样,请添加一个计数器数组,每次到达
table[i][j] = x + y;时,您都需要更新这些计数器 -
是的,我需要它来显示每个硬币可以有多少组合的信息。例如 1 美分:1251251 种组合 2 美分:432423 种组合等
-
计数器数组和硬币数组的大小应该相等吗?每个计数器对应一个硬币?
-
@KoKsMAN 如果你有工作代码并想知道如何改进它,请在SE Code Review提问。
-
@πάνταῥεῖ 他正在为一个非常具体的问题寻找解决方案,所以这里是主题。将其移至Code Review 毫无意义。
标签: c++ algorithm dynamic-programming