I have the recursive solution for knapsack problem in java, here's my code:
public class OptimalIncome{
final static int length[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final static int price[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
public static int totalLength = 9;
public static int bestCut(int i, int totalLength){
if(i < 0){
return 0;
}
else if(length[i] > totalLength){
return bestCut(i - 1, totalLength);
}
else{
return Math.max(bestCut(i - 1, totalLength), bestCut(i - 1, totalLength - length[i]) + price[i]);
}
}
public static void main(String[] args){
System.out.println("Given total rod length : " + totalLength);
System.out.println("Maximum income : " + bestCut(price.length-1, totalLength));
System.out.println("Smaller part sets : ");
}
}
It works just fine, as you can see I want to print the set of choices (smaller parts). How can I do that? Thanks