博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LintCode-Backpack
阅读量:5126 次
发布时间:2019-06-13

本文共 1593 字,大约阅读时间需要 5 分钟。

Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack? 

Note

You can not divide any item into small pieces.

Example

If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select 2, 3 and 5, so that the max size we can fill this backpack is 10. If the backpack size is 12. we can select [2, 3, 7] so that we can fulfill the backpack.

You function should return the max size we can fill in the given backpack.

Analysis:

DP.

boolean d[i][j]: From the first i items, can we select some items so that their weight equals to j.

d[i][j] = d[i-1][j] || d[i-1][j-A[i-1]].

d[0][0] = true;

We can use 1D array to perform the DP.

d[j] = d[j] || d[j-A[i-1]].

NOTE: for 1D array, the j must be decreased from m to 0 rather increasing from 0 to m!

Solution:

1 public class Solution { 2     /** 3      * @param m: An integer m denotes the size of a backpack 4      * @param A: Given n items with size A[i] 5      * @return: The maximum size 6      */ 7     public int backPack(int m, int[] A) { 8         if (A.length==0) return 0; 9         10         int len = A.length;11         boolean[] size = new boolean[m+1];12         Arrays.fill(size,false);13         size[0] = true;14         for (int i=1;i<=len;i++)15             for (int j=m;j>=0;j--){16                 if (j-A[i-1]>=0 && size[j-A[i-1]])17                     size[j] = size[j-A[i-1]];18             }19 20         for (int i=m; i>=0;i--)21             if (size[i]) return i;22 23         return 0;24     }25 }

 

  

转载于:https://www.cnblogs.com/lishiblog/p/4183806.html

你可能感兴趣的文章
POJ 2728 Desert King [最优比率生成树]
查看>>
CF585E. Present for Vitalik the Philatelist [容斥原理 !]
查看>>
[上下界网络流]【学习笔记】
查看>>
APM代码学习笔记2:编译过程
查看>>
node.js安装调试终端
查看>>
MOOC《Python网络爬虫与信息提取》学习过程笔记【requests库】第一周1-3
查看>>
final、finally和finalize的区别
查看>>
[题解]Mail.Ru Cup 2018 Round 1 - A. Elevator or Stairs?
查看>>
ABAP术语-Purchase Order
查看>>
通用权限管理设计篇_设计模式
查看>>
git分支的创建、删除、切换、合并
查看>>
SpringBoot学习(四)-->SpringBoot快速入门,开山篇
查看>>
接口测试相关知识
查看>>
蓝桥杯决赛第一题
查看>>
vue下axios和fetch跨域请求
查看>>
好的开始
查看>>
利用FFmpeg转压视频的说明
查看>>
测试课程总结2017
查看>>
chaotic and twirly用法
查看>>
ThreadLocal
查看>>