解題思路
dp[s]為剛好投入s元的序列數,dp[0]=1代表空序列。
對每個s由小到大,依最後一枚是1、2、5元,累加dp[s−1]、dp[s−2]、dp[s−5],負索引項不計。
每個非空序列具有唯一最後一枚,刪掉它就得到對應較小金額序列,因此三類互斥且完整。與不分順序的零錢組合題不同,外層必須枚舉金額。
O(r)時間、O(r)空間。 Python一次讀入另佔O(輸入文字長度)空間。
Step-by-step animation
示例:只有[1]。
步驟 1 / 3
金額1
只有[1]。
dp0=1
dp1=1
- 金額
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int r;
cin >> r;
vector<long long> d(r + 1);
d[0] = 1;
for (int s = 1; s <= r; s++)
for (int c : {1, 2, 5})
if (s >= c)
d[s] += d[s - c];
cout << d[r] << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。