由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 01 Knapsack brute force code
相关主题
问一到题目问道编程题
今天听来的一个题问个算法题2
BB的面试题-只用&和| 如何reverse a bit string?subset sum的问题
问2道面试题求解一道面试题
再来讨论一个题!一道coding test题
关于n个数的所有和的一个问题Amazon interview question.(3)
谁给个不是brute force的解法DP解法的题目是不是肯定是多项式的?
一道Google题求助一道FB的高频题non-overlap jobs
相关话题的讨论汇总
话题: int话题: valuesum话题: weights话题: weightsum
进入JobHunting版参与讨论
1 (共1页)
e****e
发帖数: 418
1
The idea is to explore all the combinations of weights array by masking and
bit shifting.
i.e. v1=5 w1=3, v2=3 w2=2, v3=4 w3=1, we form the two arrays as follows:
values[5, 3, 4], weights[3, 2, 1], W = 5.
for weights array[3, 2, 1], we want the all subsets of the elements.
such as:
[](no element)
[1]
[2]
[3]
[1 2]
[1 3]
[2 3]
[1 2 3]
We can get this subsets by masking bit by bit if we think of the array
bitwise.
[3 2 1]
0 0 0 -> (no element)
0 0 1 -> [1]
0 1 0 -> [2]
1 0 0 -> [3]
1 0 1 -> [1 3]
... ..
The code is simple. Here it is. Any suggestion is welcome.
public int knapsack01BruteForce(int[] values, int[] weights, int W) {
int numOfCombinations = (int) Math.pow( 2, weights.length );

int maxValueSum = Integer.MIN_VALUE;
for ( int i = 0; i < numOfCombinations; i++ ) {
int mask = i;
int weightSum = 0;
int valueSum = 0;

for ( int j = 0; j < weights.length; j++ ) {
int isIncluded = mask & 1; // isInclude is 0 or 1.
weightSum += weights[j] * isIncluded;
valueSum += values[j] * isIncluded;
mask >>= 1;
}

if ( weightSum <= W && valueSum > maxValueSum)
maxValueSum = valueSum;
}

return maxValueSum;
}
1 (共1页)
进入JobHunting版参与讨论
相关主题
求助一道FB的高频题non-overlap jobs再来讨论一个题!
Amazon面筋关于n个数的所有和的一个问题
算法题求教谁给个不是brute force的解法
问个关于二分图的算法一道Google题
问一到题目问道编程题
今天听来的一个题问个算法题2
BB的面试题-只用&和| 如何reverse a bit string?subset sum的问题
问2道面试题求解一道面试题
相关话题的讨论汇总
话题: int话题: valuesum话题: weights话题: weightsum