背包问题的递归与非递归算法

背包问题的基本描述是: 有一个背包,能盛放的物品总重量为S,设有N件物品,其重量分别为w1,w2,…,wn.希望从N件物品中选择若干件物品,所选物品的重量之和恰能放入该背包,即所选物品的重量之和等于S。

程序1:递归算法

#include <iostream>
#include <stdlib.h>

using namespace std;

const int N=7;
const int S=20;
int w[N+1]={0,1,4,3,4,5,2,7};

int knap(int s,int n)
{
    if(s==0)return 1;
    if(s<0||(s>0&&n<1))return 0;
    if(knap(s-w[n],n-1))
    {
        cout<<w[n];
        return 1;
    }
    return knap(s,n-1);   
}

int main(int argc, char *argv[])
{
  if(knap(S,N))cout<<endl<<“OK”<<endl;
  else cout<<“NO”<<endl;
  system(“PAUSE”); 
  return 0;
}

程序2:非递归算法

#include <iostream>
#include <stdlib.h>

using namespace std;

const int N=7;
const int S=20;
int w[N+1]={0,1,4,3,4,5,2,7};

typedef struct{
    int s;
    int n;
    int job;
    }KNAPTP;
   
int knap(int s,int n)
{
    KNAPTP stack[100],x;
    int top,k,rep;
    x.s=s;
    x.n=n;
    x.job=0;
    top=1;
    stack[top]=x;
    k=0;
    while(k==0&&top>0){
        x=stack[top];
        rep=1;
        while(!k&&rep){
            if(x.s==0)k=1;
            else if(x.s<0||x.n<=0)rep=0;
            else {
                x.s=x.s-w[x.n–];
                x.job=1;
                stack[++top]=x;
                }
            }
            if(!k){
                rep=1;
                while(top>=1&&rep){
                    x=stack[top–];
                    if(x.job==1){
                        x.s+=w[x.n+1];
                        x.job=2;
                        stack[++top]=x;
                        rep=0;
                        }
                    }
                }
        }
        if(k){
            while(top>=1){
                x=stack[top–];
                if(x.job==1)cout<<w[x.n+1];
                }
            }
            return k;
    }
int main(int argc, char *argv[])
{
  if(knap(S,N))cout<<endl<<“OK”<<endl;
  else cout<<“NO”<<endl;
  system(“PAUSE”); 
  return 0;
}

 

    原文作者:递归算法
    原文地址: https://blog.csdn.net/oracle_microsoft/article/details/1604462
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞