0/1背包問題 遞歸思想+備忘錄 好理解


#include <bits/stdc++.h>
using namespace std;

int memo[1000][1000]={0};

int knapSack(int weight[],int value[],int index,int capacity){ 
    if(index<=0 || capacity<=0) return 0;
    
    if(memo[index][capacity] !=0){
        return memo[index][capacity];
    }
    
    // 不包含第index個物品所得的價值 
    int res = knapSack(weight,value,index-1,capacity); 
    // 包含第index個物品所得的價值
    if(weight[index]<=capacity)
    {
    res = max(res,value[index]+knapSack(weight,value,index-1,capacity-weight[index])); 
    }
    
    //添加子問題的解,便於下次直接使用
    memo[index][capacity] = res;
    return res;
}

int main(){
    int n,c;   // 第一行為n值和c值,表示n件物品和背包容量c
    cin>>n>>c;
    int weight[1000];
    int value[1000];
    
    for(int i=1;i<=n;i++){  //每行有兩個數據,分別表示第i(1≤i≤n)件物品的重量和價值。
        cin>>weight[i]>>value[i];
    }
    
    cout<<knapSack(weight,value,n,c)<<endl;
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM