b370中等

CSES 1636|硬幣組合二(Coin Combinations II)

以動態規劃逐步構成目標金額或點數。

解題思路

以動態規劃逐步構成目標金額或點數。

每個面額的數量決定唯一組合。先枚舉硬幣,再讓金額由小到大更新dp[s]+=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

Reference solution

回報程式錯誤

完整程式

#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;
    vector<int> d(x + 1);
    d[0] = 1;
    for (int v : c)
        for (int s = v; s <= x; s++) {
            d[s] += d[s - v];
            if (d[s] >= 1000000007)
                d[s] -= 1000000007;
        }
    cout << d[x] << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多