0/1 knapsack problem

Problem statement

Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?

Solution

0/1 knapsack problem is a classical dynamic programming model. There is a knapsack with the capacity of m, you should find the maximum volume can be filled in. 

Still, we need:

  • DP memory and the representation
  • The initialization of DP memory
  • DP formula
  • Return value.

DP memory and the representation

Suppose, size is the number of elements in A.

A two dimension array: dp[size + 1][m + 1]

  • dp[i][j]: means the maximum volume formed by first i elements whose volume is at most j.

The key word is the first and at most. 

  • The first means there are i + 1 elements.
  • At most means the total volume can not exceed j.

Initialization

For a two dimension DP memory, normally, we should initialize the first row and column, and start from i = 1 and j = 1. The initialization comes from general knowledge.

  • dp[0][i]: first 0 elements can form at most i volume. Obviously, the initialization is 0 since we can get nothing if there is no elements.
  • dp[i][0]: first i elements can form at most 0 volume. Obviously, the initialization is 0 since we can get 0 volume by any elements.

DP formula

For current element A[i], we need to know what is the maximum volume can get if we add it into the backpack.

  • dp[i][j] = dp[i - 1][j] if A[i - 1] is greater than j
  • dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - A[i - 1]]) if j >= A[i - 1], we find the maximum value.

Return value.

Just return dp[size][m]

Time complexity is O(size * m)

class Solution {
public:
    /**
     * @param m: An integer m denotes the size of a backpack
     * @param A & V: Given n items with size A[i] and value V[i]
     * @return: The maximum value
     */
    int backPackII(int m, vector<int> A, vector<int> V) {
        // write your code here
        // write your code here
        int size = A.size();
        //vector<vector<int>> dp(size + 1, vector<int>(m + 1, 0));
        int dp[size + 1][m + 1] = {};
        for(int i = 1; i <= size; i++){
            for(int j = 1; j <= m; j++){
                dp[i][j] = dp[i - 1][j];
                if(j >= A[i - 1]){
                    dp[i][j] = max(dp[i][j], V[i - 1] + dp[i - 1][j - A[i - 1]]);
                }
            }
        }
        return dp[size][m];
    }
};

 

转载于:https://www.cnblogs.com/wdw828/p/6919446.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值