簡體   English   中英

如何在Java中使用遞歸實現背包問題

[英]How to implement knapsack problem with recursion in java

因此,如果您不了解背包問題是什么,則可以采用這種方法從背包中提取不同的重量,以使它們的總和等於指定的總重量。 這是我書中的一個示例,說明如果指定的總重量為20,如何解決問題。

鏈接到我書中的圖片

如果有人知道如何使用遞歸PLEASE幫助在Java中實現此問題,我會感到困惑。 這是我開始的內容,但是我很確定這是錯誤的,而且我不知道現在要去哪里。

import java.util.*;

public class n01044854 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please first enter a weight capacity up to a value of 
100, followed by a series of individual weight values with 25 weights being the max.)
");
        String values = input.nextLine();
        String[] tokens = values.split(" +");

        int capacity = Integer.parseInt(tokens[0]);
        int[] weightValues = new int[tokens.length - 1];
        for (int i = 0; i < tokens.length - 1; i++)
            weightValues[i] = Integer.parseInt(tokens[i+1]);
        optimizeWeights(capacity, weightValues, 0);
    }

    public static void optimizeWeights(int target, int[] weights, int currentIndex) {
        if (weights[currentIndex] == target)
            System.out.println("Success! Knapsack optimally filled.");
        else if (weights[currentIndex] < target) {
            int newTarget = target - weights[currentIndex];
            optimizeWeights(newTarget, weights, currentIndex + 1);
        } else if (weights[currentIndex] > target) {
            if (currentIndex < weights.length - 1)
                optimizeWeights(target, weights, currentIndex + 1);
            else
            //confused on what to do 
        }
    }
}

看例子

我在准備進行技術采訪時就已經實施了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM