当前位置: 首页 > news >正文

Coin Change

一、题目

Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and 1-cent. We want to make changes with these coins for a given amount of money.

For example, if we have 11 cents, then we can make changes with one 10-cent coin and one 1-cent coin, or two 5-cent coins and one 1-cent coin, or one 5-cent coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of making changes for 11 cents with the above coins. Note that we count that there is one way of making change for zero cent.

Write a program to find the total number of different ways of making changes for any amount of money in cents. Your program should be able to handle up to 100 coins.
Input
The input file contains any number of lines, each one consisting of a number ( ≤250 ) for the amount of money in cents.
Output
For each input line, output a line containing the number of different ways of making changes with the above 5 types of coins.
Sample
Inputcopy Outputcopy
11
26
4
13

二、分析

题意要求使用五种面值的硬币,组成不同金额能有多少组合的方法
题目中有一个条件,硬币的数量不能超过100。
那么下面这种递推的方法就不能够控制硬币是数量

//错误代码
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=1e3+5;
int dp[maxn];
int a[5]={1,5,10,25,50};
int main()
{int n;while(cin>>n){memset(dp,0,sizeof(dp));dp[0]=1;for(int i=0;i<5;i++)for(int j=a[i];j<=n;j++){dp[j]=dp[j]+dp[j-a[i]];}cout<<dp[n]<<endl;}
}

定义dp[i][j]表示i枚硬币组成j有的方法总数
这样就可以控制硬币的数量

//正确代码
#include <iostream>
#include <cstring>
using namespace std;
int dp[110][260];
// dp[i][j]表示i枚硬币组成j有的方法总数
int a[6] = {1, 5, 10, 25, 50};
int main()
{int n;while (cin >> n){memset(dp, 0, sizeof(dp));dp[0][0] = 1;for (int i = 0; i < 5; i++)for (int j = a[i]; j <= n; j++)for (int k = 1; k <= 100; k++){dp[k][j] += dp[k - 1][j - a[i]];}int ans = 0;for (int i = 0 ;i<= 100; i++)//要从0开始{ans += dp[i][n];}cout << ans << endl;}
}
http://www.lryc.cn/news/123330.html

相关文章:

  • 2023 8 -14链表OJ
  • 大数据必回之LSM树
  • Vue中的Object.defineProperty详解
  • MySQL高阶知识点(一)一条SQL【更新】语句是如何执行的
  • threejs实现模型gltf的动画效果
  • Harmony创建项目ohpm报错
  • 44 | 酒店预订及取消的数据分析
  • 物联网和不断发展的ITSM
  • 加了ComponentScan,但是feign接口无法注入的原因
  • C#Winform中DataGridView控件显示行号实例
  • Stable Diffusion WebUI安装和使用教程(Windows)
  • LeetCode 35题:搜索插入位置
  • Linux系统中常见的几种软件包管理器
  • python异步IO完全指南
  • 打造企业或者个人IP引流法
  • TMC Self-Managed 提升跨多云环境安全性
  • 并发编程 - 线程间三种常见的通信手段
  • iperf3命令使用说明
  • 华纳云:美国Linux服务器磁盘分区备份的操作方式
  • Arrays类
  • lua ipairs pairs
  • swift3.0 废弃 swift 4.0 以后字符串截取
  • 休息是不可能休息的
  • Java面向对象(内部类)(枚举)(泛型)
  • macOS - 安装 GNU make、cmake
  • vue中style scoped属性的作用
  • 【ARM 嵌入式 编译系列 10.2 -- 符号表与可执行程序分离详细讲解】
  • Gin各种参数接收
  • 【Python】进阶之 MySQL入门教程
  • Word 2019打开.doc文档后图片和公式不显示(呈现为白框)的解决办法