如何知道背包问题(DP实现)中选择了哪个项目?

时间:2019-06-23 04:22:13

标签: java algorithm dynamic-programming knapsack-problem

我正在基于此代码实现背包问题,我想知道最终选择了哪些项目。

代码:

await demo_schema_download.call();
const import_files_download = [];
for (const step of fake_data.steps_to_import) {
  let response;
  let file_counter = 1;
  do {
    response = await download_demo_file({
      demo_handle: 'demo-2',
      step,
      file_counter
    }).call();
    file_counter++;
  } while (response.remaining_number_of_files > 0);
  import_files_download.push(response); // is this needed?
}
return import_files_download; // is this needed?

我想做的是根据最初存储在背包中的物品找到最终插入到背包中的物品,并将这些结果以二进制格式存储在文件中。

我的意思是,这里我们在这段代码中有3个项目,例如,如果项目编号1(值为60的项目)和项目编号3(值为120的项目)是最终选择,我想得到一个类似于1,0,1的字符串

1 个答案:

答案 0 :(得分:0)

您可以在return语句之前将以下内容添加到代码中:

        int ind = n;
        int weight = W;
        String s = "";
        while (ind > 0) {
            if (K[ind][weight] != K[ind - 1][weight]) {
                s = "1," + s;
                weight -= wt[ind - 1];
            }
            else {
                s = "0," + s;
            }
            ind -= 1;
        }
        s = s.substring(0, s.length() - 1);
        System.out.println(s);

此代码实质上从最终解决方案回溯,以查看i个项目的最大值是否等于i-1个项目的最大值(指示是否使用了第i个项目)。

将其添加到您的代码中后,我得到以下输出,这似乎是正确的:

0,1,1
220
相关问题