In: Computer Science
Urgent! How do you do solve a knapsack problem recursively in JAVA. for an arbitrary knapsack capacity and series of weights. Assume the weights are sorted in an array. **The arguments to the knapsack function are target weight and the array index where the remaining items start. For example if you want your knapsack to weigh exactly 20 pounds and you have five items with weights of 11,8,7,6 and 5 pounds. In this case only combination that works is 8, 7 and 5 pounds. Please show without using import library classes
0/1 knapsack problem
The knapsack problem in its simplest form involves trying to fit items of different weights into a knapsack so that the knapsack ends up with a specified total weight
class
tryknap{
static
int
max(
int
a,
int
b) {
return
(a
> b) ? a : b; }
static
int
knapSack(
int
W,
int
wt[],
int
val[],
int
n)
{
if
(n ==
0
|| W ==
0
)
return
0
;
if
(wt[n -
1
] > W)
return
knapSack(W, wt, val, n -
1
);
else
return
max(val[n -
1
] + knapSack(W - wt[n
-
1
], wt, val, n -
1
),
knapSack(W,
wt, val, n -
1
));
}
public
static
void
main(String
args[])
{
int
val[] =
new
int
[] {
11,8,7,6,5
};
int
wt[] =
new
int
[]
{
8
, 7
, 5
};
int
W = 20
;
int
n = val.length;
System.out.println(knapSack(W,
wt, val, n));
}
}