当前位置:网站首页>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];
}
}
边栏推荐
- Basic operation and question type summary of linked list
- 习题8-8 判断回文字符串 (20 分)
- Superscalar processor design yaoyongbin Chapter 2 cache -- Excerpt from subsection 2.4
- Introduction to MySQL transactions
- 206. reverse linked list
- 如果重来一次高考,我要好好学数学!
- 【数据挖掘时间序列分析】餐厅销量预测
- 二叉树的基本操作与题型总结
- Exercise 6-6 using a function to output an integer in reverse order (20 points)
- Dynamics 365 选项集操作
猜你喜欢

360 online enterprise security cloud is open to small, medium and micro enterprises for free

Basic operation and question type summary of binary tree

什么是死锁?(把死锁给大家讲明白,知道是什么,为什么用,怎么用)

5.学城项目 支付宝支付

Analysis of the implementation principle of an open source markdown to rich text editor

Tkinter学习笔记(三)

Players must read starfish NFT advanced introduction
![[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 (II)
随机推荐
习题6-2 使用函数求特殊a串数列和 (20 分)
[data mining time series analysis] restaurant sales forecast
Players must read starfish NFT advanced introduction
批改网高分短语&句型
Point cloud read / write (2): read / write TXT point cloud (space separated | comma separated)
Daily question - Roman numeral to integer
习题9-1 时间换算 (15 分)
Matplotlib和tkinter学习笔记(一)
Optimization of quick sort
图书管理系统
Learning bit segment (1)
C language to achieve eight sorts (2)
Conception du Processeur superscalaire Yao yongbin chapitre 2 cache - - sous - section 2.4 extrait
STM32开发笔记112:ADS1258驱动设计——读寄存器
Exercise 9-6 statistics of student scores by grade (20 points)
Implementation stack and queue
Precision twist jitter
926. 将字符串翻转到单调递增
【NodeJs】Electron安装
Neglected technique: bit operation