完全背包问题。
代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
long long dp[30055];
int coin[5] = {1, 5, 10, 25, 50};
int main()
{
int num;
dp[0] = 1;
for(int i=0; i<5; ++i)
{
for(int j=0; j<30001; ++j)
dp[j + coin[i]] += dp[j];
}
while(scanf("%d", &num) != EOF)
{
if(dp[num] != 1)
printf("There are %lld ways to produce %d cents change.\n", dp[num], num);
else
printf("There is only %lld way to produce %d cents change.\n", dp[num], num);
}
return 0;
}

本文通过C++实现了一个解决完全背包问题的程序。利用动态规划算法,计算了使用面额为1、5、10、25和50美分硬币组合成不同金额的方法数量。代码展示了如何迭代更新状态,最终输出所有可能的组合方式。
255

被折叠的 条评论
为什么被折叠?



