蛮力法 ----- 背包问题(Knapsack Problem)
1.问题描述:
有n 个物品,它们有各自的重量和价值,现有给定容量的背包,如何让背包里装入的物品具有最大的价值总和?(物体不可以拆分,装就必须装完整的。)
Given n items of known weights w 1 , w 2 , . . . , w n and values v 1 , v 2 , . . . , v n and a knapsack of capacity W,
find the most valuable subset of the items that fit into the knapsack.
2.解决办法
最简单的方式就是把所有拿商品的方式都列出来,最后再做判断此方法是否满足装包条件,并且通过比较和记录找出最优解和解组成(如果满足则记录此时的价值和装的方式,当下一次的装法优于这次,则更新记录,如此下去到最后便会找到最优解,同时解组成也找到);
The exhaustive-search approach to this problem leads to generating all the subsets of the set of n items given, computing the total weight of each subset in order to identify feasible subsets(i.e., the ones with the total weight not exceeding the knapsack capacity), and finding a subset of the largest value among them.
3.例子
W = 10(背包的总容量)
4个物体:weight分别为7, 3, 4, 5;value分别是:42, 12 , 40 , 25;
经过计算,列举出了所有的可能情况,经过计算和比较,选取3.4两个物体的总价值max是65;即为答案
4.时间复杂度分析
n件商品,共有n(n-1)/2种可能,故蛮力法的效率是指数级别的,可见效率很低;
蛮力法效率低不建议采取,但可以用于检验小规模的动态规划解背包问题的正确性和可行性,如下图输出可见,解01背包问题用动态规划是可行的:
Since the number of subsets of an n-element set is 2^n , the exhaustive search leads to a O(2^n) algorithm, no matter how efficiently individual subsets are generated.