C++背包示例

/*
*   description:背包示例
*               一个大小为17的背包,有5类不同大小与价值的物品,求使得背包中的物品价值最大的组合
*               item    A    B    C    D    E
*               size    3    4    7    8    9
*               value    4    5    10    11    13
*
*   writeby:    nick
*   date:       2012-10-22 23:56
*/
#include <iostream>
#include <string.h>
#define N 5
using namespace std;

typedef struct
{
    int size; int val;
} Item;

Item items[5]={{3,4},{4,5},{7,10},{8,11},{9,13} };

int knap(int cap)
{
    int i,space,max,t;
    max = 0;
    for(i=0; i<N; i++)
    {
        if((space = cap-items[i].size) >=0 )
            if((t=knap(space) + items[i].val)>max)
                max = t;
    }
    return max;
}

int main()
{
    cout << knap(17);
    return 0;
}

改进后:

/*
*   description:背包示例
*               一个大小为17的背包,有5类不同大小与价值的物品,求使得背包中的物品价值最大的组合
*               item    A    B    C    D    E
*               size    3    4    7    8    9
*               value    4    5    10    11    13
*
*   writeby:    nick
*   date:       2012-10-22 23:56
*/
#include <iostream>
#include <string.h>
#define N 5   //物品个数
#define M 17  //容量

using namespace std;

typedef struct
{
    int size; int val;
} Item;

Item items[5]={{3,4},{4,5},{7,10},{8,11},{9,13} };
int maxKnown[M] = {0};

int knap(int cap)
{
    int space,max,t;
    if(maxKnown[cap] != 0 ) return maxKnown[cap];

    max = 0;
    for(int i=0; i<N; i++)
    {
        if((space = cap-items[i].size) >=0 )
            if((t=knap(space) + items[i].val)>max)
            {
                max = t;
            }
    }
    maxKnown[cap] = max;
    return max;
}

int main()
{
    memset(maxKnown, 0, sizeof(maxKnown));
    cout << knap(M);
    return 0;
}

方法:

1. 使用递归

2. for遍历每个物品,求出空量space,使用该space递归求出最大值value,如果value+items[i].value>max,修改max的值

3. 返回max

改进: 用静态数组保存对应space的max值。

原文地址:https://www.cnblogs.com/wouldguan/p/2734915.html