Three simple knapsack problem

01 backpack

Given the value of n and the weight of the item, the capacity determined when the backpack when m, the maximum value can be loaded

You can only take at most once for each item

 

One-dimensional wording

dp array represents the maximum value of the current state can be put down

for(int i=0;i<n;i++)
{
    for(int j=m;j>=w[i];j--)
    {
           dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
    }
}

 

 

Full backpack

Given the value of n and the weight of the item, the capacity determined when the backpack when m, the maximum value can be loaded

Each item can be taken multiple times

 

One-dimensional wording

for(int i=0;i<n;i++)
{
     for(int j=w[i];j<=m;j++)
    {
        dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
    }
}            

 

A dimensional difference between the writing and the complete backpack backpack 01 wherein the second layer loop traversal order for loop

01 Backpack: m from the start -

Completely backpack: From w [i] ++ Start

 

Multiple backpack

Guess you like

Origin www.cnblogs.com/OFSHK/p/11976780.html