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

Coin Combinations II(Dynamic Programming)

题目描述

Consider a money system consisting of n coins. Each coin has a positive integer value. Your task is to calculate the number of distinct ordered ways you can produce a money sum x using the available coins.
For example, if the coins are {2,3,5} and the desired sum is 9, there are 3 ways:

2+2+5
3+3+3
2+2+2+3

输入

The first input line has two integers n and x: the number of coins and the desired sum of money.
The second line has n distinct integers c1,c2,...,cn: the value of each coin.
Constraints
1 ≤ n ≤ 100
1 ≤ x ≤ 10^6
1 ≤ ci ≤ 10^6

输出

Print one integer: the number of ways modulo 10^9+7.

样例输入
3 9
2 3 5
样例输出
3

思路分析

与题目Coin Combinations II(Dynamic Programming)稍有不同。

外层循环遍历硬币面额,对于每一个硬币面额 j

内层循环从该硬币面额 j 开始遍历到目标金额 x,对于每个目标金额 i,更新 dp[i] 的值。状态转移方程为 dp[i] += dp[i - j],表示使用当前硬币面额 j 可以凑出金额 i 的组合数等于不使用该硬币时凑出金额 i 的组合数加上使用该硬币时凑出金额 i - j 的组合数。

每次更新后,对 dp[i] 取模,避免溢出。

代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll N=1e6+1;
const ll mod=1e9+7;
ll n,x;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n>>x;vector<ll>a(n,0);for(ll i=0;i<n;i++){cin>>a[i];}sort(a.begin(),a.end());vector<ll>dp(N,0);dp[0]=1;for(ll&j:a){for(ll i=j;i<=x;i++){dp[i]+=dp[i-j];dp[i]%=mod;}}cout<<dp[x];return 0;
}
http://www.dtcms.com/a/313118.html

相关文章:

  • LLM - AI大模型应用集成协议三件套 MCP、A2A与AG-UI
  • 用 Eland 在 Elasticsearch Serverless 部署 Learning-to-Rank 排序模型
  • 数据,正在成为AI大模型最后的护城河
  • leetcode 2106. 摘水果 困难
  • Rust 同步方式访问 REST API 的完整指南
  • 道格拉斯-普克算法 - 把一堆复杂的线条变得简单,同时尽量保持原来的样子
  • python---赋值、浅拷贝、深拷贝
  • 【C 学习】03-你的第一个C程序
  • 上位机知识篇---脚本文件
  • Linux环境下使用Docker搭建多服务环境
  • Corrosion2靶场
  • xxljob总结
  • Obsidian结合CI/CD实现自动发布
  • 1、docker容器命令 | 生命周期管理
  • NX969NX972美光固态闪存NX975NX977
  • python 12 install jupyter时zmq.h或libzmq报错处理
  • MVCC:数据库事务隔离的 “时空魔法”
  • nvm切换本地nodejs环境
  • node中shapefile字符集判断
  • Sklearn 机器学习 数据聚类 KMeans实现聚类
  • wav音频格式中,ACM波形、A/mu-Law Wave、Windows PCM、Microsoft ADPCM的区别
  • 《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——9. 接入真实硬件:驱动USB摄像头
  • LeetCode 分类刷题:2824. 统计和小于目标的下标对数目
  • Go语言--语法基础7--函数定义与调用--自定义函数
  • Go语言实战案例:TCP服务器与客户端通信
  • HoloLens+vuforia打包后遇到的问题
  • 图像、视频、音频多模态大模型中长上下文token压缩方法综述
  • Connection refused: no further information: localhost/127.0.0.1:2375
  • Git的安装和配置
  • JavaWeb开发