背包问题

在n个物品中挑选若干物品装入背包,最多能装多满?如果背包的大小为m,每一个物品的大小为A[i]

您在真实的面试中是否遇到过这个题? 
Yes
例子

假设有4个物品[2, 3, 5, 7]

假设背包的大小为11,能够选择[2, 3, 5]装入背包,最多能够装满10的空间。

假设背包的大小为12。能够选择[2, 3, 7]装入背包,最多能够装满12的空间。

函数须要返回最多能装满的空间大小。

注意

你不能够将物品进行分割。

标签 Expand  

相关题目 Expand 


分析:这题就真的是直接上01背包的模板即可啦

代码:

class Solution {
public:
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A: Given n items with size A[i]
     * @return: The maximum size
     */
    int backPack(int m, vector<int> A) {
        // write your code here
        int *dp = new int[m+1];
        fill(dp,dp+m+1,-1);
        dp[0]=0;
        for(auto x:A)
        {
            for(int i=m;i>=x;i--)
            {
                if(dp[i-x]!=-1)
                    dp[i]=1;
            }
        }
        int ret = m;
        while(dp[ret]==-1)
            ret--;
        delete[] dp;
        return ret;
    }
};


posted on 2016-01-09 10:38  gcczhongduan  阅读(201)  评论(0编辑  收藏  举报