数字组合

https://www.acwing.com/problem/content/280/

\(01背包变式\)

\(f[i][j]:表示在前i个中选,选出的数和为j的个数.\)

for (int i = 1; i <= n; ++i) f[i][0] = 1;
for (int i = 1; i <= n; ++i)
    for (int j = m; j >= 0; --j) {
        if (j >= a) f[i][j] += f[i - 1][j - a];
        else f[i][j] = f[i - 1][j];
    }

然后可以省去一维.

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 10010; 
int f[N];
 
int main() {
    IO;
    int n, m
    cin >> n >> m;;
    f[0] = 1;
    for (int i = 1; i <= n; ++i) {
        int a;
        cin >> a;
        for (int j = m; j >= a; --j) 
            f[j] += f[j - a];
    }
    cout << f[m] << '\n';
    return 0;
}

posted @ 2021-04-12 21:21  phr2000  阅读(98)  评论(0编辑  收藏  举报