题解都是一维的,来个比较容易理解的朴素的二维
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 105;
int n, m, v[N], f[N][N];
int main()
{
cin >> m >> n;
memset(f, 0x3f, sizeof(f));
for (int i = 0; i <= n; ++i)
f[i][0] = 0;
for (int i = 1; i <= n; ++i)
cin >> v[i];
for (int i = 1; i <= n; ++i)
for (int j = 0; j <= m; ++j)
if (j >= v[i])
f[i][j] = min(f[i-1][j], f[i-1][j-v[i]] + 1);
else
f[i][j] = f[i-1][j];
if (f[n][m] == 0x3f3f3f3f)
cout << 0 << endl;
else
cout << f[n][m] << endl;
return 0;
}