Using backtracking to solve the Knapsack Problem

Source: Internet
Author: User

I have recently finished using the Backtracking Method to Solve the eight queens problem, and finally successfully solved 92 solutions. Then I am looking at the greedy solution to the backpack problem. I suddenly thought that I could actually use the backtracking method to solve the problem, in essence, the backtracking method is an exhaustive method.

The result obtained by the backtracking method must be correct, which can also verify the correctness of the greedy algorithm.

Problem description:

Set wmax to the maximum weight. W [] (0 ~ N-1) is numbered 0 ~ N-1 cargo weight, V [] (0 ~ N-1) for its value, X [] for its solution,

Obtain Vmax = Σ Xi * VI under wn = Σ Xi * WI <wmax.

The Code is as follows:

// Maximum value of global variables: int maxvalue = 0;
// The current optimal solution int an_x [10]; // W is the weight array
// VA is the value Array
// Wmax is the maximum weight
// N indicates the number of goods
// N_w does not include the weight of the current cargo
// X is a set of solutions.
// Value is the value that is not included in the value of the current Goods
// Index the index of the current cargo
Void get_max_sample (int * w, int * va, int wmax, int N, int n_w, int * X, int value, int index) {int I; if (Index = 10) {If (maxvalue <value) {for (I = 0; I <10; I ++) an_x [I] = x [I]; maxvalue = value;} return;} for (I = 0; I <2; I ++) {x [Index] = I; if (n_w + I * W [Index] <wmax) {get_max_sample (W, VA, wmax, N, n_w + I * W [Index], X, value + I * va [Index], index + 1) ;}x [Index] = 0 ;}}
// Solve the instance
// Get_max_sample (W, VA, 20, 10, 0, x, 0 );
//

 

Time Complexity Analysis:

Since the number of recursive executions is twice, the time complexity is T (2n). Therefore, it is feasible to use N in a small case, the number of instance goods to be solved is 10, t = 210 = 1024, and the actual number of operations must be less than this value.

 

Greedy Algorithm solution:

 

 

  

Using backtracking to solve the Knapsack Problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.