0/1 knapsack Problem's dynamic programming method solves, the predecessor's statement prepares, here does the work, but oneself realizes once according to the understanding, the main goal is to exercise the thinking and the programming ability, simultaneously, also is in order to enhance to the dynamic programming law mechanism understanding and grasps.
A question worth mentioning is whether, when implemented in JAVA, it is modeled by an algorithmic model, or modeled with an object model? If the algorithm model is used, then the value and weight of the backpack are deposited directly into two arrays, and if the object model is used, then the knapsack and knapsack problems are modeled on the object. Reasoning, or using the object model, although the heart feels the algorithm model seems better. Sometimes this is true, although the object model is now very mainstream, but it is not omnipotent, using other models and perspectives, may be better solution.
Backpack Modeling:
Package Algorithm.dynamicplan;public class Knapsack {/** backpack weight */private int weight;/** Backpack Item value */private int value;/*** * constructor */public knapsack (int weight, int value) {this.value = Value;this.weight = weight;} public int getweight () {return weight;} public int GetValue () {return value;} Public String toString () {return "[Weight:" + weight + "" + "value:" + value + "]"; }}
Knapsack Problem Solving:
/** * Solve knapsack problem: * Given n backpack, the weight of the w1,w2,......, WN, respectively, the value of V1,v2,......, vn * To put in the total load-bearing for the box of Totalweight, * for the bag can be put into the maximum value of the backpack value. * * Note: The use of dynamic programming method to solve knapsack problem * Set the first n backpack, the total load-bearing of J is the best value of v[n,j], the best solution pack composed of b[n]; * Solve the optimal value: * 1. If J < Wn, then: v[n,j] = v[n-1,j]; * 2. If J >= wn, then: v[n,j] = max{v[n-1,j], vn + v[n-1,j-wn]}. * * Solve the optimal pack composition: * 1. If V[N,J] > v[n-1,j] then backpack n is selected into B[n], * 2. Then solve the former n-1 backpack into the total load of j-wn, * So should judge V[n-1, J-wn] VS V[n-2,j-wn], decide whether the backpack N-1 is selected. * 3. Push backward until the total load is zero. * Focus: Master the method of solving the problem by using dynamic programming method and realization idea. * Analysis Method: The optimal solution S (n) of the problem instance p (N) contains the optimal solution S (n-1) of the problem case p (n-1); * Constructs S (n) * Realization idea on the basis of S (n-1): iterative solution from bottom up and memory-based top-down recursive */package algorithm.dynamicplan;import JAVA.UTIL.A Rraylist;public class Knapsackproblem {/** designated backpack */private knapsack[] bags;/** total load */private int totalweight;/** given backpack quantity * /private int n;/** Top n backpack, total load-bearing for totalweight optimal value Matrix */private int[][] bestvalues;/** top n backpack, total load-bearing is totalweight optimal value */priva te int bestvalue;/** Top n Backpack, the total load-bearing for the totalweight of the optimal solution composition */privAte arraylist<knapsack> bestsolution;public knapsackproblem (knapsack[] bags, int totalweight) {this.bags = bags; This.totalweight = TOTALWEIGHT;THIS.N = bags.length;if (bestvalues = = null) {bestvalues = new int[n+1][totalweight+1];}} /** * solves the knapsack problem of the first n backpacks, given the total load bearing of totalweight * */public void Solve () {System.out.println ("given backpack:"); for (knapsack b:bags) {Sys Tem.out.println (b);} System.out.println ("Given total load:" + totalweight);//solve the optimal value for (int j = 0; J <= Totalweight; J + +) {for (int i = 0; I <= N; i++) {if (i = = 0 | | j = = 0) {Bestvalues[i][j] = 0;} else {//If the first backpack weighs more than the total load, the optimal solution exists in the front i-1 backpack,//NOTE: The first I backpack is bags[i-1]if (J < Bags[i-1].getweight ()) {Bestvalues[i][j] = BESTVALUES[I-1][J];} else {//If the I backpack is not greater than the total load, then the optimal solution is either the optimal solution containing the knapsack,//or the optimal solution of the first knapsack, whichever is the maximum, using the classification discussion method//I backpack weight iweight and value ivalueint I Weight = Bags[i-1].getweight (); int ivalue = Bags[i-1].getvalue (); Bestvalues[i][j] = Math.max (Bestvalues[i-1][j], Ivalue + bestvalues[i-1][j-iweight]);} else}//else}//for}//for//Solve knapsack composition if (bestsolution = = null) {bestsolution = new arraylist<knapsack> ();} int tempweight = Totalweight; for (int i=n; I >= 1; i--) {if (Bestvalues[i][tempweight] > Bestvalues[i-1][tempweight]) {Bestsolution.add (bag S[i-1]); BAGS[I-1] denotes the first I backpack tempweight-= Bags[i-1].getweight (); } if (tempweight = = 0) {break;} } bestvalue = Bestvalues[n][totalweight]; }/** * Get top N Backpacks, total load-bearing for totalweight the optimal solution value of the knapsack problem * Calling Condition: The solve method must be called first * */public int getbestvalue () {return bestvalue;} /** * Get top N Backpacks, total load-bearing for totalweight knapsack problem the optimal solution matrix * Call Condition: must first call the Solve method * */Public int[][] Getbestvalues () {RE Turn bestvalues; }/** * Get top N Backpacks, total load-bearing for totalweight the optimal solution matrix of the knapsack problem call condition: The solve method must be called first * */public arraylist<knapsack> Getbestsolution () {return bestsolution; }}
Knapsack problem Test:
Package Algorithm.dynamicplan;public class Knapsacktest {public static void main (string[] args) {knapsack[] bags = new Kna Psack[] {new knapsack (2,13), new Knapsack (1,10), new Knapsack (3,24), new Knapsack (2,15), new Knapsack (4,28), New Knapsack ( 5,33), new Knapsack (3,20), New Knapsack (1, 8)};int totalweight = 12; Knapsackproblem KP = new Knapsackproblem (bags, totalweight); Kp.solve (); System.out.println ("--------The solution of the knapsack problem example:---------"); SYSTEM.OUT.PRINTLN ("Optimal value:" + kp.getbestvalue ()); SYSTEM.OUT.PRINTLN ("Optimal solution" selected backpack ":"); System.out.println (Kp.getbestsolution ()); System.out.println ("Best Value Matrix:"); int[][] bestvalues = Kp.getbestvalues (); for (int i=0; i < bestvalues.length; i++) {for (i NT J=0; J < Bestvalues[i].length; J + +) {System.out.printf ("%-5d", Bestvalues[i][j]);} System.out.println ();}}}
Summary of Dynamic programming method:
1. The dynamic programming method is used to solve non-optimization problems:
When the solution of a problem instance P (n) is composed of a solution of a child problem instance, such as P (n) = P (n-1) + P (n-2) [Fibonacci sequence], and P (n-1) and P (n-2) may contain coincident sub-problems, you can use the dynamic programming method, through the bottom-up iteration, the solution of small sub-problem instances, And as the basis for solving the solution of large sub-problem instances. The key idea is to avoid solving the problem of sub-duplication.
For example: To find the Fibonacci number F (5):
F (5) = f (4) + F (3);
Sub-Problem: f (4) = f (3) + F (2);
F (3) = f (2) + f (1);
F (2) = f (1) + f (0)
F (2) = f (1) + f (0);
Sub-Problem: f (3) = f (2) + F (1)
F (2) = f (1) + f (0)
It is shown from the above calculation that the sub-problem F (2) is repeated for 2 times if recursion is used purely, and that the iterative sub-problem solving takes a lot of unnecessary time when the problem instance is large. If the dynamic programming method is used to store the value of F (2), it can save a lot of time when the subsequent calculation needs to be taken out directly.
Another typical example is the solution of the two-polynomial coefficients C (n, k) = C (N-1, K) + C (n-1, k-1)
2. The dynamic programming method solves the optimization problem:
When the optimal solution of the problem instance p (N) can be constructed from the optimal solution of the problem instance P (n-1), the dynamic programming method can be used to construct the optimal solution in one step.
The key is to master dynamic programming method to solve the problem of the analysis method, how to derive a recursive solution from the problem. In fact, when the return of the knapsack problem recursive, then the work is much simpler, how to analyze the knapsack problem, the derivation of the optimal solution of the recursive type, I think, this is the most important place! Problem analysis is important!
0/1 knapsack problem by dynamic programming method to solve--java realization