Coin Combinations I(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 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 8 ways:
2+2+5
2+5+2
5+2+2
3+3+3
2+2+2+3
2+2+3+2
2+3+2+2
3+2+2+2
输入
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
样例输出
8
思路分析
动态规划。
从1到x,找出所有金额的硬币组合方法。
初始化dp[0]=1,便于后期i=j的情况下直接添加一种方法。
本题样例解析:
i=1时,没有小于等于1的硬币金额,dp[1]=0.
i=2时,j=2,dp[2]+=dp[2-2],dp[2]=1.
i=3时,j=2,dp[3]+=dp[3-2],dp[3]=0; j=3,dp[3]+=dp[3-3],dp[3]=1.
i=4时,j=2,dp[4]+=dp[4-2],dp[4]=1; j=3,dp[4]+=dp[4-3],dp[4]=1.
i=5时,j=2,dp[5]+=dp[5-2],dp[5]=1; j=3,dp[5]+=dp[5-3],dp[5]=2;
j=5,dp[5]+=dp[5-5],dp[5]=3.
i=6时,j=2,dp[6]+=dp[6-2],dp[6]=1; j=3,dp[6]+=dp[6-3],dp[6]=2;
j=5,dp[6]+=dp[6-5],dp[6]=2.
i=7时,j=2,dp[7]+=dp[7-2],dp[7]=2; j=3,dp[7]+=dp[7-3],dp[7]=4;
j=5,dp[7]+=dp[7-5],dp[7]=5.
i=8时,j=2,dp[8]+=dp[8-2],dp[8]=2; j=3,dp[8]+=dp[8-3],dp[8]=5;
j=5,dp[8]+=dp[8-5],dp[8]=6.
i=9时,j=2,dp[9]+=dp[9-2],dp[9]=5; j=3,dp[9]+=dp[9-3],dp[9]=7;
j=5,dp[9]+=dp[9-5],dp[9]=8.
代码
#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 i=1;i<=x;i++){for(ll&j:a){if(j>i)break;dp[i]+=dp[i-j];dp[i]%=mod;}}cout<<dp[x];return 0;
}