牛客 NC15948 (dfs)

一共有n个物品, 第i个物品的体积为v[i];

有一个背包容量为m,现在我要挑选一些物品放入这个背包

我现在知道在总体积不超过背包容量的情况下,他一共有多少种放法(总体积为0也算一种放法)。
输入
3 10
1
2
4
输出
8
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=200200;
LL v[N];
LL ans;
LL n,m;
void dfs(LL sum,LL idx)
{
    if(idx>n)//当选择物品的时候都已经超过了可以选择的东西的时候,那么我们就可以返回去让他增加一次数据
    {
        ans++;
        return;
    }
    //如果在当前物品加下去也不会有任何的不对劲的时候,就让他加下去
    //这里可以看作是附加条件
    if(sum+v[idx]<=m) dfs(sum+v[idx],idx+1);
    //因为不加是一档可以的,所以不能用else
    dfs(sum,idx+1);
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    while(cin>>n>>m)
    {
        for(LL i=1;i<=n;i++)
            cin>>v[i];
        ans=0;
        dfs(0,1);//当体积为0的时候也有一种情况
        cout<<ans<<endl;
    }
    return 0;
}
posted @ 2022-07-27 17:50  高尔赛凡尔娟  阅读(20)  评论(0编辑  收藏  举报