背包问题(递归的使用)

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int knap(int W[],int T,int n){
    if(T==0) return 1;
    if(T<0||(T>0&&n<1)) return 0;
    if(knap(W,T-W[n-1],n-1)==1){
        printf("第%d个物品,体积为:%d\n",n,W[n-1]);
        return 1;
    }return knap(W,T,n-1);//每一步为0 都会删除对应的后向
} 
int main(void)
{
    int T=10,n=6,W[6]={0,3,6,0,7,9};
    knap(W,T,n);
    return 0;
    }

猜你喜欢

转载自www.cnblogs.com/yzbpxx/p/10543874.html