題目: UVa - 357 - Let Me Count The Ways

題目說明

有面額 [1, 5, 10, 25, 50] 的錢幣,給一個 n,求 n 有幾種不同的組合方式。

Input: 每行為一組測資,一個整數表示 n

Output: 輸出 n 有幾種不同的組合方式。

解題思路

DP 的 Coin Change 問題,核心概念為枚舉每一個最後加入的面額。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>

using namespace std;

static auto __ = []
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}();

long long money[] = { 1, 5, 10, 25, 50 };
long long dp[30001];

void CoinChange()
{
dp[0] = 1;
for (auto& m : money) for (auto i = m; i <= 30000; ++i)
dp[i] += dp[i - m];
}

void solve()
{
int n;
while (cin >> n)
{
if (dp[n] == 1) cout << "There is only 1 way ";
else cout << "There are " << dp[n] << " ways ";
cout << "to produce " << n << " cents change.\n";
}
}

int main()
{
CoinChange();
solve();
}