蛮力法求解简单背包问题

 从穷举的思路出发,通过求出number件物品的所有组合,并判断每一组合的物品体积是否等于背包容量ratedCapaticy,即可求出问题的解。
 思路:
 数组array中array[1]~array[number]分别存放number件物品的体积,result为全局数组,用以存放当前求出的组合。
 算法中combination函数对数组array的元素下标1~number求取palces个组合位数的所有组合,当求得一组组合时,判断
 相应的数组array的元素和是否等于ratedCapacity,若其和为ratedCapacity则输出该组元素;通过调用combination函数,
 对元素下标1~number分别求得取1到number-1全部组合,则可以求得全部解。

 1 int result[MAXNUM];     // result存放组合数的全局数组,result[0]存放组合位数
 2 
 3 /**
 4  * 判定各种组合情况(分治法、递归)
 5  * { array[1]~array[number]存放number件物品的体积,retaedCapacity表示背包容量,places表示组合位数 }
 6  */
 7 void combination(int array[], int number, int ratedCapacity, int places)
 8 {
 9     /* 组合的代码实现 */
10     for(int place = number; place >= places; --place) {                     // 依次选定组合中的最大者
11         result[places] = place;
12         if(places > 1) {                                                    /* 组合的位数还不够,递归继续求 */
13             combination(array, (place - 1), ratedCapacity, (places - 1));
14         } else {                                                            /* 求得一个组合,接下来判定是否满足要求 */
15             int currentVolumes = 0;
16             for(int index = result[0]; index > 0; --index) {                // 以组合中的数为下标,求出array中相应的元素和
17                 currentVolumes += array[result[index]];
18             }
19             if(currentVolumes == ratedCapacity) {                           // 元素和等于背包容量,输出该组数组array元
20                 for(int i = result[0]; i > 0; --i) 
21                     cout << array[result[i]] << ", ";
22                 cout << endl;
23             }
24         }
25     }
26 }
27 
28 /**
29  * 求解简单背包问题
30  */
31 void package(int array[], int number, int ratedCapacity)
32 {
33     int currentVolumes = 0;
34     for(int index = 1; index <= number; ++index)                            // 求出全部物品的体积 
35         currentVolumes += array[index];
36     if(currentVolumes == ratedCapacity) {                                   // 全部物品正好装入背包,不需求物品组合情况
37         for(int index = 1; index <= number; ++index)
38             cout << array[index] << ", ";
39         cout << endl;
40         return ;
41     }
42     /* 背包不是正好装下全部物品,求出各件物品组合情况 */
43     for(int index = 1; index < number; ++index) {                            
44         result [0] = index;
45         combination(array, number, ratedCapacity, index);
46     }
47 }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值