当前位置:网站首页>0-1 knapsack problem of dynamic programming (detailed explanation + analysis + original code)
0-1 knapsack problem of dynamic programming (detailed explanation + analysis + original code)
2022-06-11 22:27:00 【InfoQ】
️0-1 knapsack problem ️
Topic details
Input : N = 3, V = 4, v = [4,2,3], w = [4,2,3]
Output : 4
explain : Select only the first item , Can maximize value .
Input : N = 3, V = 5, v = [4,2,3], w = [4,2,3]
Output : 5
explain : Not the first item , Select the second and third item , Can maximize value .
Their thinking
simple 0-1 Knapsack general solution
idp[i][j]ijiivjdp[0][j]=vdp[0][j]=0iv[i]w[i]- There is not enough space left in the backpack , Then the item cannot be selected at this time ,.
- There is enough space left in the backpack , Then the total value of the goods at this time is.
/**
*
* @param N Number of items
* @param C Backpack Capacity
* @param v The volume of each piece
* @param w The value of everything
* @return The greatest value
*/
public int zoKnapsack(int N, int C, int[] v, int[] w) {
//0-1 The backpack is simple
int[][] dp = new int[N][C+1];
// initialization
for (int j = 0; j <= C; j++) {
dp[0][j] = j >= v[0] ? w[0] : 0;
}
// Process the remaining elements
for (int i = 1; i < N; i++) {
for (int j = 0; j <= C; j++) {
// No election
int x = dp[i-1][j];
// choose
int y = j >= v[i] ? dp[i-1][j-v[i]] + w[i] : 0;
// Take the maximum of the two
dp[i][j] = Math.max(x, y);
}
}
return dp[N-1][C];
}
Optimization plan
ncnc2ci%2i&1&%i&1 public int zoKnapsackPlus(int N, int C, int[] v, int[] w) {
//0-1 Knapsack rolling array optimization
int[][] dp = new int[2][C+1];
// initialization
for (int j = 0; j <= C; j++) {
dp[0][j] = j >= v[0] ? w[0] : 0;
}
// Process the remaining elements
for (int i = 1; i < N; i++) {
for (int j = 0; j <= C; j++) {
// No election
int x = dp[(i-1) & 1][j];
// choose
int y = j >= v[i] ? dp[(i-1) & 1][j-v[i]] + w[i] : 0;
// Take the maximum of the two
dp[i&1][j] = Math.max(x, y);
}
}
return dp[(N-1) & 1][C];
}
iji-1jj-v[i]jjj-v[i]
dp[j]dp[j]dp[j]dp[j-v[i]]dp[j]dp[j-v[i]]dp[j-v[i]]dp[j]dp[j]dp[j-v[i]]jj>=v[i]v[i] public int zoKnapsackOnePlus(int N, int C, int[] v, int[] w) {
//0-1 Knapsack rolling array optimization
int[] dp = new int[C+1];
// initialization
for (int j = 0; j <= C; j++) {
dp[j] = j >= v[0] ? w[0] : 0;
}
// Process the remaining elements
for (int i = 1; i < N; i++) {
for (int j = C; j >= v[i]; j--) {
// No election
int x = dp[j];
// choose
int y = dp[j-v[i]] + w[i];
// Take the maximum of the two
dp[j] = Math.max(x, y);
}
}
return dp[C];
}
practice : To divide into equal and subsets
nums Input :nums = [1,5,11,5]
Output :true
explain : Arrays can be divided into [1, 5, 5] and [11] .
Input :nums = [1,2,3,5]
Output :false
explain : An array cannot be divided into two elements and equal subsets .
1 <= nums.length <= 200
1 <= nums[i] <= 100
Problem solving
numsnumsnumssumsumfalsesumsum/2sum/2sum/2- First step , Find the sum of elements within
sum/2Maximum element sum in case .
- The second step , Determine whether the sum of elements is equal to
sum/2.
c=sum/2numsdp[i][j]ijiivjdp[0][j]=vdp[0][j]=0inums[i]nums[i]- There is not enough space left in the backpack , Then the item cannot be selected at this time ,.
- There is enough space left in the backpack , Then the total value of the goods at this time is.
- Find the sum of the elements of the array
sum, IfsumFor the even , Then go to the next step , Otherwise return tofalse.
- Convert to 0-1 knapsack , At a maximum capacity of
sum/2Under the circumstances , Value and capacity are a one-to-one relationship, seeking the maximum value .
- Define the State , Determine the initial transition .
- According to the state transfer equationCalculate the maximum element sum .
- Determine whether the maximum element sum is consistent with
sum/2equal .
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
int[][] dp = new int[n][c+1];
for (int j = 0; j <= c; j++) {
dp[0][j] = j >= nums[0] ? nums[0] : 0;
}
for (int i = 1; i < n; i++) {
for (int j = 0; j <= c; j++) {
int pre = dp[i-1][j];
int cur = j >= nums[i] ? dp[i-1][j-nums[i]] + nums[i] : pre;
dp[i][j] = Math.max(pre, cur);
}
}
// 4. Determine whether the value of the final backpack is equal to sum/2, If equal, it means that it can be divided
return dp[n-1][c] == c;
}
}
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
int[][] dp = new int[2][c+1];
for (int j = 0; j <= c; j++) {
dp[0][j] = j >= nums[0] ? nums[0] : 0;
}
for (int i = 1; i < n; i++) {
for (int j = 0; j <= c; j++) {
int index = (i-1) & 1;
int pre = dp[index][j];
int cur = j >= nums[i] ? dp[index][j-nums[i]] + nums[i] : pre;
dp[i&1][j] = Math.max(pre, cur);
}
}
// 4. Determine whether the value of the final backpack is equal to sum/2, If equal, it means that it can be divided
return dp[(n-1)&1][c] == c;
}
}
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
// We found that dp[i][j] Only with dp[i-1][j] and dp[i-1][j-nums[i]] of , We can change the number of remaining spaces from 0-c Traversal changed to c-0 Traverse , Keep only the remaining space dimensions
int[] dp = new int[c+1];
for (int i = 0; i < n; i++) {
for (int j = c; j >= nums[i]; j--) {
int pre = dp[j];
int cur = dp[j-nums[i]] + nums[i];
dp[j] = Math.max(pre, cur);
}
}
// 4. Determine whether the value of the final backpack is equal to sum/2, If equal, it means that it can be divided
return dp[c] == c;
}
}
️ To divide into equal and subsets : From no more than to just
sum/2sum/2inums[i-1]class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
boolean[][] dp = new boolean[n+1][c+1];
// 4. initialization
dp[0][0] = true;
// 5. Process the remaining states
for (int i = 1; i <= n; i++) {
int val = nums[i-1];
for (int j = 0; j <= c; j++) {
// No choice
boolean no = dp[i-1][j];
// choice
boolean yes = j >= val ? dp[i-1][j - val] : false;
dp[i][j] = no || yes;
}
}
return dp[n][c];
}
}
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
boolean[][] dp = new boolean[2][c+1];
// 4. initialization
dp[0][0] = true;
// 5. Process the remaining states
for (int i = 1; i <= n; i++) {
int val = nums[i-1];
for (int j = 0; j <= c; j++) {
// No choice
int index = (i-1) & 1;
boolean no = dp[index][j];
// choice
boolean yes = j >= val ? dp[index][j - val] : false;
dp[i&1][j] = no || yes;
}
}
return dp[n&1][c];
}
}
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
// 1. Sum up
for (int x : nums) {
sum += x;
}
// 2. If sum is odd , That must not be divided
if ((sum & 1) == 1) {
return false;
}
// 3. Convert to 0-1 knapsack
int n = nums.length;
int c = sum / 2;
boolean[] dp = new boolean[c+1];
// 4. initialization
dp[0] = true;
// 5. Process the remaining states
for (int i = 1; i <= n; i++) {
int val = nums[i-1];
for (int j = c; j >= val; j--) {
dp[j] =dp[j] || dp[j - val];
}
}
return dp[c];
}
}
边栏推荐
- C language implements eight sorts (1)
- 一款开源的Markdown转富文本编辑器的实现原理剖析
- 习题11-2 查找星期 (15 分)
- Maze problem in C language
- 还在直接用 localStorage 么?该提升下逼格了
- STM32开发笔记113:ADS1258驱动设计——读取温度值
- BUUCTF(5)
- Point cloud read / write (2): read / write TXT point cloud (space separated | comma separated)
- [JS] 1347- high level usage of localstorage
- Matlab point cloud processing (XXIV): point cloud median filtering (pcmedian)
猜你喜欢

如果重来一次高考,我要好好学数学!

Introduction to MySQL transactions

图的基本操作(C语言)

Tkinter学习笔记(四)

Start notes under the Astro Pro binocular camera ROS

Fastapi 5 - common requests and use of postman and curl (parameters, x-www-form-urlencoded, raw)
![[Yu Yue education] Yancheng Normal University Advanced Algebra reference](/img/3f/cd7f6f420fb1d453acca9aa73665ba.jpg)
[Yu Yue education] Yancheng Normal University Advanced Algebra reference

Tkinter study notes (III)

論文閱讀《Dense Visual SLAM for RGB-D Cameras》

If I take the college entrance examination again, I will study mathematics well!
随机推荐
Matplotlib和tkinter学习笔记(一)
Tkinter study notes (IV)
Exercise 6-6 using a function to output an integer in reverse order (20 points)
Implementation of sequencelist sequence table
Superscalar processor design yaoyongbin Chapter 2 cache -- Excerpt from subsection 2.4
What is deadlock? (explain the deadlock to everyone and know what it is, why it is used and how to use it)
习题11-3 计算最长的字符串长度 (15 分)
Introduction to MySQL transactions
Matlab point cloud processing (XXIV): point cloud median filtering (pcmedian)
How to adjust the font blur of win10
Exercise 8-8 moving letters (10 points)
A simple example of linear regression in machine learning
LeetCode栈题目总结
[JS] 1347- high level usage of localstorage
Tkinter学习笔记(二)
Is it safe for qiniu business school to send Huatai account? Really?
消息队列入门MQ
Tkinter学习笔记(四)
Implementation stack and queue
R7-1 sum of numeric elements of a list or tuple