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 ≤
1 ≤ ci ≤
输出
Print one integer: the number of ways modulo .
样例输入
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;
}