Can not understand knapsack solutions

后端 未结 2 1509
Happy的楠姐
Happy的楠姐 2021-01-23 07:25

In wikipedia the algorithm for Knapsack is as follows:

for i from 1 to n do  
  for j from 0 to W do  
    if j >= w[i] then  
      T[i, j] := max(T[i-1, j         


        
2条回答
  •  暖寄归人
    2021-01-23 08:03

    The Dynamic Programming solution of knapsack is basically recursive:

    T(i,j) = max{ T(i-1,j) ,         T(i-1,j-w[i]) + v[i] }
           //      ^                         ^
           //  ignore the element       add the element, your value is increase
           //                           by v[i] and the additional weight you can
           //                           carry is decreased by w[i]
    

    (The else condition is redundant in the recursive form if you set T(i,j) = -infinity for each j < 0).

    The idea is exhaustive search, you start from one element and you have two possibilities: add it, or don't.
    You check both options, and chose the best of those.

    Since it is done recursively - you effectively checking ALL possibilities to assign the elements to the knapsack.

    Note that the solution in wikipedia is basically a bottom-up solution for the same recursive formula

提交回复
热议问题