Tuesday, August 11, 2015

Backpack

Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this backpack?
Have you met this question in a real interview? 
Yes
Example
If we have 4 items with size [2, 3, 5, 7], the backpack size is 11, we can select [2, 3, 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.
Note
You can not divide any item into small pieces.

Challenge
O(n x m) time and O(m) memory.
O(n x m) memory is also acceptable if you do not know how to optimize memory.


背包问题:
给n个数,问能不能装满m

状态: f[i][j]为前i个数能不能装满j
初始条件: f[0][1:] =false, f[*][0]= true;
转移方程: f[i][j]=f[i-1][j] || j-A[i]?=0? f[i-1][j-A[i]] : false
结果: 扫描f[n][m:1] 取最大



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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 n= A.size();
        bool tbl[2][m+1];
        for (int i=0; i<2; i++)
            tbl[i][0]=true;
        for (int i=1; i<=m; i++)
            tbl[0][i]=false;
        for (int i=1; i<=n; i++){
            for (int j=1; j<=m; j++){
                tbl[i%2][j]=tbl[(i-1)%2][j] ;
                if (j-A[i-1]>=0 &&  tbl[(i-1)%2][j-A[i-1]])
                    tbl[i%2][j] = true;
            }
        }
        for (int i=m; i>=0; i--){
            if (tbl[n%2][i])
                return i;
        }
        return 0;
    }
};

No comments:

Post a Comment