0
我有背包问题的解决幼稚的代码,我想选择的项目的索引列表,目前它返回选定项的值的总和。 任何帮助将不胜感激。 Java代码:如何获得所选项目的列表0-1背包?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
/* A Naive recursive implementation of 0-1 Knapsack problem */
class Knapsack
{
// A utility function that returns maximum of two integers
static int max(int a, int b) {
return (a > b)? a : b; }
// Returns the maximum value that can be put in a knapsack of capacity W
static int knapSack(float W, float wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more than Knapsack capacity W, then
// this item cannot be included in the optimal solution
if (wt[n-1] > W)
{
return knapSack(W, wt, val, n-1);
}
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else {
return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1)
);
}
}
// Driver program to test above function
public static void main(String args[])
{
int val[] = new int[]{29,74,16,55,52,75,74,35,78};
float wt[] = new float[]{85.31f,14.55f,3.98f,26.24f,63.69f,76.25f,60.02f,93.18f,89.95f};
float W = 75f;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}
当前的结果:148 预期的结果:2,7
检查此链接 - https://www.youtube.com/watch?v=8LusJS5-AGo&list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr它有一个视频教程如何做到这一点,我认为这将是更容易理解不是书面的解决方案 – monster
后来我注意到了这一点,但您的解决方案是DP的递归一个instea。所以视频中的方法不会为你工作。你可以做的就是让'参观了其中'visited'阵列[i] = 1'如果您使用的第i个元素和'0'如果没有 – monster
@monster \t 无法理解,你可以修改它的代码? –