一、01背包
例子:给你一堆物品,每个物品有一定的体积,每个物品只能选一个,求总体积不超过\(m\)的方案数。
输入
4 5
2 2 3 7
输出
7
1、二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int f[N][N];//第一维:前i个物品,第二维:体积j及以下
int main() {
cin >> n >> m;
//初始化
for (int i = 0; i <= m; i++) f[0][i] = 1;
for (int i = 1; i <= n; i++) {
int v;
cin >> v;
for (int j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v) f[i][j] += f[i - 1][j - v];
}
}
cout << f[n][m] << endl;
return 0;
}
2、一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int f[N];
int main() {
cin >> n >> m;
for (int i = 0; i <= m; i++) f[i] = 1;
for (int i = 1; i <= n; i++) {
int v;
cin >> v;
for (int j = m; j >= v; j--) f[j] = f[j] + f[j - v];
}
cout << f[m] << endl;
return 0;
}
二、完全背包
例子:给你一堆物品,每个物品有一定的体积,每个物品可以选无数多个,求总体积不超过\(m\)的方案数
输入
3 5
2 3 7
输出
5
1、二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int f[N][N];
int main() {
cin >> n >> m;
for (int i = 0; i <= m; i++) f[0][i] = 1;
for (int i = 1; i <= n; i++) {
int v;
cin >> v;
for (int j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v) f[i][j] += f[i][j - v];
}
}
cout << f[n][m] << endl;
return 0;
}
2、一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int n, m;
int f[N];
int main() {
cin >> n >> m;
for (int i = 0; i <= m; i++) f[i] = 1;
for (int i = 1; i <= n; i++) {
int v;
cin >> v;
for (int j = v; j <= m; j++) f[j] = f[j] + f[j - v];
}
cout << f[m] << endl;
return 0;
}