Personal summary of dynamic programming

The programming problems encountered during the internship recruitment ended up stuck in dynamic programming. I have seen some dynamic programming posts, and the previous conceptual things are all understood by individuals, so I won't repeat them here.


When to use dynamic programming? (As far as the written test questions are concerned, it is more difficult to read the questions. When you don't know where to start, you usually use dynamic programming to do it.) Of course, you should look at some problem characteristics and the like...


sample1: The knapsack problem (01 knapsack, complete knapsack, multiple knapsacks) has N items and a knapsack with a capacity of V. The capacity of the ith item is c[i] and the value is w[i]. Ask which items Putting in the backpack can make the sum not exceed the backpack capacity, and the sum of the value is the largest. The problem is mainly the sum of the maximum value. As for which items to choose, you can re-judge the printout later. The following analysis is the dynamic programming method to find the maximum sum part

01 Backpack (each item can only be taken once): In the face of each item, there are only states of taking and not taking. Use a two-dimensional array dp[i][j] to represent the maximum value that can be obtained when facing the i-th item and the knapsack capacity remaining j. Of course, the number in the lower right corner of the two-dimensional array is the maximum value dp[N][V] that can be obtained.

For each dp[i][j], it is first divided into whether the remaining capacity of the backpack contains the i-th item: j<c[i], this item cannot be taken, dp[i][j]=dp [i-1][j]; j>=c[i], if the item can be put down, start to consider the value, compare the two values ​​of taking and not taking, and take the largest value, dp[i][j ]=max{dp[i-1][j], dp[i-1][jc[i]]+w[i]}.

Complete backpack (unlimited use of each item): The only difference from the 01 backpack is that the second layer cycle is different, and the value of j is c[i] to V

Multiple backpacks (the i-th item has a corresponding quantity): it can be converted into a 01 backpack, add a layer of loop, set the number of items dp[i][j]=max{dp[i-1][j], dp[ i-1][jk*c[i]]+k*w[i]}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324703935&siteId=291194637