c – 获取背包DP矩阵中所选项目的列表

我已经尝试实现堆栈溢出
Answered Solution.但它不起作用.

测试用例 :

   int val[] = {10,40,30,50};
   int wt[] = {5,4,6,3};
     W = 10;

OUTPUT KNAPSACK DP MATRIX:

0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 5 5 5 5 5 5 
0 0 0 0 4 5 5 5 5 9 9 
0 0 0 0 4 5 6 6 6 9 10 
0 0 0 3 4 5 6 7 8 9 10 

Wt that can be reached is : 10

sum of wt of selected items : 11 (which is wrong should be only 10)

selected -> 6 (3rd item) and 5 (1st item) [which is wrong]

int knapSack(int W, int wt[], int val[], int n)
{
 int i, w;
 int K[n+1][W+1]; 
  int picks[n+1][W+1] = {0};
  // Build table K[][] in bottom up manner
  for (i = 0; i <= n; i++)
   {
   for (w = 0; w <= W; w++)
   {
       if (i==0 || w==0)
           K[i][w] = 0;
       else if (wt[i-1] <= w){
          //val[i-1 ] is value of curr i
             K[i][w] = max(wt[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);
             if (val[i-1]+K[i-1][w-wt[i-1]] > K[i-1][w]){
                picks[i][w]=1;
             }
            else
                picks[i][w]=-1;
       }
       else{
        // wt of individual is > limit 
             picks[i][w] = -1; 
             K[i][w] = K[i-1][w];
    }
   }
  }
}

为了打印拾取的元素,我正在使用

while (w > 0 && i > 0 ){

if ((K[i][w] - K[i-1][w-wt[i-1]]) == wt[i-1]){
    weight += wt[i-1];
    i = i - 1;
    w = w - wt[i-1];
}
else{
  i = i - 1;
}

}

最佳答案

 w =  w - wt[i-1] 

实际上是

w =  w - wt[i-2] 

因为i = i – 1是在它之前计算的.
下面的代码现在可以使用.

    weight += wt[i-1];
    i = i - 1;
    w = w - wt[i] ;
点赞