解题思路
代码
原始做法 O(N^3)
#include <iostream>
using namespace std;
const int N = 1010;
int a[5] = {0, 10, 20, 50, 100};
int f[5][N];
int main() {
int m;
cin >> m;
f[0][0] = 1;
for (int i = 1; i <= 4; i++) {
f[i][0] = 1;
for (int j = 1; j <= m; j++) {
for (int k = 0; j >= k * a[i]; k++) {
f[i][j] += f[i - 1][j - k * a[i]];
}
}
}
cout << f[4][m] << endl;
return 0;
}
优化时间 O(N^2)
#include <iostream>
using namespace std;
const int N = 1010;
int a[5] = {0, 10, 20, 50, 100};
int f[5][N];
int main() {
int m;
cin >> m;
f[0][0] = 1;
for (int i = 1; i <= 4; i++) {
f[i][0] = 1;
for (int j = 1; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= a[i]) f[i][j] += f[i][j - a[i]];
}
}
cout << f[4][m] << endl;
return 0;
}
优化空间
#include <iostream>
using namespace std;
const int N = 1010;
int a[5] = {0, 10, 20, 50, 100};
int f[N];
int main() {
int m;
cin >> m;
f[0] = 1;
for (int i = 1; i <= 4; i++) {
for (int j = a[i]; j <= m; j++) {
f[j] += f[j - a[i]];
}
}
cout << f[m] << endl;
return 0;
}