Question: I am solving the knapsack problem using recusrison. All numbers provided by user are on one line. first number is target weight followed by the
I am solving the knapsack problem using recusrison. All numbers provided by user are on one line. first number is target weight followed by the nubers that need to be inserted into an array(ie, 20 15 10 10 5 4). My program works perfectly right now when I know the amount of array elements the user will enter after the target weight (right now set to 5). Problem is I will not know how many numbers will need to go into array. I am using an array list for the recursion. How do I use an array list for the input and tranfer to recusion??
import java.util.*; import java.io.*;
public class Program4{
public static int arrayItems[]; public static ArrayList
knapsack(target, 0); }
public static void knapsack(int target, int i){
if (i == (arrayItems.length)){ //base condition to stop the recursion
//If the target weight is 0 then displays the values if (target == 0){ System.out.println("The solution of recursive knapsack problem is by filling with weights: "); for (int j = 0; j < values.size(); j++){ System.out.print(values.get(j) + "\t");}
System.out.println();}
return;}
//if the i'th element is exist then the move the weights(arrayItems)
//into values
values.add(arrayItems[i]);
knapsack(target - arrayItems[i], i + 1);
values.remove(values.size() - 1);
knapsack(target, i + 1);
}}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
