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

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

Given n items with size A[i], an integer m denotes the size of a backpack. How full you can fill this backpack? NoteYou can not divide any item into small pieces.ExampleIf 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.

DP.

boolean d[i][j]:  For the first i items, can we fill a backpack of size j? true or false.

d[i][j] = d[i-1][j] || (j>=A[i-1] && 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!

2D code:

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         // write your code here 9         boolean[][] res = new boolean[A.length+1][m+1];10         res[0][0] = true;11         for (int i=1; i<=A.length; i++) {12             for (int j=0; j<=m; j++) {13                 res[i][j] = res[i-1][j] || (j-A[i-1]>=0 && res[i-1][j-A[i-1]]);14             }15         }16         for (int j=m; j>=0; j--) {17             if (res[A.length][j]) return j;18         }19         return 0;20     }21 }

1D code:

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 }

 

转载地址:http://edmhl.baihongyu.com/

你可能感兴趣的文章
思科认证——网络工程师
查看>>
elasticsearch安装
查看>>
su,passwd,ls,timestamp,cd,type,hash的简要整理
查看>>
【转】eclipse打不开,提示错误“Error:could not open 'D:\JAVA\JDK\lib\i386\jvm.cfg'"
查看>>
我的友情链接
查看>>
【×××系列五】multipoint Gre Over Ipsec 配置详解
查看>>
KVM的基本使用情况
查看>>
clonezilla搭建
查看>>
SpringMvc笔记
查看>>
MM们改掉不好的生活习惯 瘦肚子其实很简单
查看>>
Windows 2008 DHCP中继(Relay)
查看>>
RHEL6字符模式安装图形界面
查看>>
修改3389端口
查看>>
小鸟chacha初学linux 第一课(5) 常规文件操作
查看>>
python中time类型,datetime类型的关系与互相转换
查看>>
zabbix中文配置指南
查看>>
mapreduce 词频统计
查看>>
Linux正则表达式——扩展篇
查看>>
我的友情链接
查看>>
E1线路知识要点
查看>>