解題思路
以動態規劃逐步構成目標金額或點數。
先枚舉金額s,再枚舉最後一枚硬幣c。移除最後一枚後是金額s−c的合法排列,且不同最後硬幣互斥,故dp[s]=sum dp[s−c]。
空序列或空組合是湊成0的唯一方法,dp[0]=1;每次加總對10^9+7取模。
時間 O(nx),空間 O(x+n),含輸入硬幣。
Step-by-step animation
面額 [1,3]、目標5:比較組合與排列
步驟 1 / 3
步驟 1
示例面額1、3,目標5;dp[0]=1。
空排列或空組合1種
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, x;
cin >> n >> x;
vector<int> c(n);
for (int &v : c)
cin >> v;
sort(c.begin(), c.end());
vector<int> d(x + 1);
d[0] = 1;
for (int s = 1; s <= x; s++)
for (int v : c) {
if (v > s)
break;
d[s] += d[s - v];
if (d[s] >= 1000000007)
d[s] -= 1000000007;
}
cout << d[x] << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。