神奇的口袋(DP or DFS)

版权声明:转载请注明出处链接 https://blog.csdn.net/qq_43408238/article/details/89511205

描述

有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。

输入

输入的第一行是正整数n (1 <= n <= 20),表示不同的物品的数目。接下来的n行,每行有一个1到40之间的正整数,分别给出a1,a2……an的值。

输出

输出不同的选择物品的方式的数目。

样例输入

3
20
20
20

样例输出

3

因为最近刚学了搜索嘛,所以一开始用dfs试了试,过了,但是在过程中参数的变化过程还是有些模棱两可。

思路:每件物品有两种方案,选和不选(你想到了什么),直接深搜就可以了。

dfs Code:

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include <algorithm>
#include <stdlib.h>
#include <cstdio>
#include<sstream>
#include<cctype>
#include <set>
#include<queue>
#include <map>
#include <iomanip>
#define  INF  0x3f3f3f3f
#define mmt(a,b)  memset(a,b,sizeof(a))
typedef long long ll;
const ll MAX=1000000;
using namespace std;
ll t,v[50];ll sum=0;
void dfs(ll totle,ll index)
{
    if(totle==0) {++sum;return ;}//注意:这一句放在前边,下边index>t,否则index>t+1,
    if(index>t) return ;//表面看来无关紧要,但是按现在顺序比那样可节省3倍时间
    totle-=v[index];
    dfs(totle,index+1);//选
    totle+=v[index];
    dfs(totle,index+1);//不选

}
int main()
{
    cin>>t;
   for(ll i=1;i<=t;i++)
    cin>>v[i];
   dfs(40,1);
   cout<<sum;
}

    然后是回溯法,和dfs差不多吧。

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include <algorithm>
#include <stdlib.h>
#include <cstdio>
#include<sstream>
#include<cctype>
#include <set>
#include<queue>
#include <map>
#include <iomanip>
#define  INF  0x3f3f3f3f
#define mmt(a,b)  memset(a,b,sizeof(a))
typedef long long ll;
const ll MAX=1000000;
using namespace std;
ll t,v[50];ll sum=0;
int ways(int w,int k)//从前k种物品中选取一些,凑成体积w做法数目
{
    if(w==0) return 1;
    if(k<=0) return 0;
    return ways(w,k-1)+ways(w-v[k],k-1);
}
int main()
{
    cin>>t;
    for(ll i=1;i<=t;++i)
    {
        cin>>v[i];
    }
    cout<<ways(40,t);
    return 0;
}

每件物品选或不选,当然要联想到动态规划问题喽

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include <algorithm>
#include <stdlib.h>
#include <cstdio>
#include<sstream>
#include<cctype>
#include <set>
#include<queue>
#include <map>
#include <iomanip>
#define  INF  0x3f3f3f3f
#define mmt(a,b)  memset(a,b,sizeof(a))
typedef long long ll;
const ll MAX=1000000;
using namespace std;
ll dp[50][50];//dp[i][j]从前j个物品凑出体积i的方法数
ll v[50];
ll N;
int main()
{
    cin>>N;
    mmt(dp,0);
    for(ll i=1;i<=N;++i)
    {
        cin>>v[i];
        dp[0][i]=1;//边界条件
    }
    dp[0][0]=1;
    for(ll i=1;i<=40;++i)
        for(ll j=1;j<=N;++j)
    {
        dp[i][j]=dp[i][j-1];
        if(i>=v[j]) dp[i][j]+=dp[i-v[j]][j-1];
    }
    cout<<dp[40][N];
}


猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/89511205