码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode backpack

时间:2015-01-14 08:29:24      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:

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

注意

You can not divide any item into small pieces.

样例

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.

解法:

背包问题。

f(j)=max(f(j=wi)+vi, f(j))

public class Solution {
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    public int backPack(int m, int[] A) {
        // write your code here
        int[] result=new int[m+1];
	        for(int i=0;i<A.length;i++){
	        	for(int j=m;j>=A[i];j--){
	        		result[j]=Math.max(result[j-A[i]]+A[i], result[j]);
	        	}
	        }
	        return result[m];
    }
}

  

lintcode backpack

标签:

原文地址:http://www.cnblogs.com/lilyfindjobs/p/4223061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!