translation: Add Python and Java code for EN version (#1345)

* Add the intial translation of code of all the languages

* test

* revert

* Remove

* Add Python and Java code for EN version
This commit is contained in:
Yudong Jin
2024-05-06 05:21:51 +08:00
committed by GitHub
parent b5e198db7d
commit 1c0f350ad6
174 changed files with 12349 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
/**
* File: climbing_stairs_backtrack.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.*;
public class climbing_stairs_backtrack {
/* Backtracking */
public static void backtrack(List<Integer> choices, int state, int n, List<Integer> res) {
// When climbing to the nth step, add 1 to the number of solutions
if (state == n)
res.set(0, res.get(0) + 1);
// Traverse all choices
for (Integer choice : choices) {
// Pruning: do not allow climbing beyond the nth step
if (state + choice > n)
continue;
// Attempt: make a choice, update the state
backtrack(choices, state + choice, n, res);
// Retract
}
}
/* Climbing stairs: Backtracking */
public static int climbingStairsBacktrack(int n) {
List<Integer> choices = Arrays.asList(1, 2); // Can choose to climb up 1 step or 2 steps
int state = 0; // Start climbing from the 0th step
List<Integer> res = new ArrayList<>();
res.add(0); // Use res[0] to record the number of solutions
backtrack(choices, state, n, res);
return res.get(0);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsBacktrack(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
}
}

View File

@@ -0,0 +1,36 @@
/**
* File: climbing_stairs_constraint_dp.java
* Created Time: 2023-07-01
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_constraint_dp {
/* Constrained climbing stairs: Dynamic programming */
static int climbingStairsConstraintDP(int n) {
if (n == 1 || n == 2) {
return 1;
}
// Initialize dp table, used to store subproblem solutions
int[][] dp = new int[n + 1][3];
// Initial state: preset the smallest subproblem solution
dp[1][1] = 1;
dp[1][2] = 0;
dp[2][1] = 0;
dp[2][2] = 1;
// State transition: gradually solve larger subproblems from smaller ones
for (int i = 3; i <= n; i++) {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
}
return dp[n][1] + dp[n][2];
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsConstraintDP(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
}
}

View File

@@ -0,0 +1,31 @@
/**
* File: climbing_stairs_dfs.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_dfs {
/* Search */
public static int dfs(int i) {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2)
return i;
// dp[i] = dp[i-1] + dp[i-2]
int count = dfs(i - 1) + dfs(i - 2);
return count;
}
/* Climbing stairs: Search */
public static int climbingStairsDFS(int n) {
return dfs(n);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDFS(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
}
}

View File

@@ -0,0 +1,41 @@
/**
* File: climbing_stairs_dfs_mem.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class climbing_stairs_dfs_mem {
/* Memoized search */
public static int dfs(int i, int[] mem) {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2)
return i;
// If there is a record for dp[i], return it
if (mem[i] != -1)
return mem[i];
// dp[i] = dp[i-1] + dp[i-2]
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
// Record dp[i]
mem[i] = count;
return count;
}
/* Climbing stairs: Memoized search */
public static int climbingStairsDFSMem(int n) {
// mem[i] records the total number of solutions for climbing to the ith step, -1 means no record
int[] mem = new int[n + 1];
Arrays.fill(mem, -1);
return dfs(n, mem);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDFSMem(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
}
}

View File

@@ -0,0 +1,48 @@
/**
* File: climbing_stairs_dp.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_dp {
/* Climbing stairs: Dynamic programming */
public static int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// Initialize dp table, used to store subproblem solutions
int[] dp = new int[n + 1];
// Initial state: preset the smallest subproblem solution
dp[1] = 1;
dp[2] = 2;
// State transition: gradually solve larger subproblems from smaller ones
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* Climbing stairs: Space-optimized dynamic programming */
public static int climbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int tmp = b;
b = a + b;
a = tmp;
}
return b;
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDP(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
res = climbingStairsDPComp(n);
System.out.println(String.format("There are %d solutions to climb %d stairs", n, res));
}
}

View File

@@ -0,0 +1,72 @@
/**
* File: coin_change.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class coin_change {
/* Coin change: Dynamic programming */
static int coinChangeDP(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize dp table
int[][] dp = new int[n + 1][amt + 1];
// State transition: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transition: the rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// The smaller value between not choosing and choosing coin i
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* Coin change: Space-optimized dynamic programming */
static int coinChangeDPComp(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize dp table
int[] dp = new int[amt + 1];
Arrays.fill(dp, MAX);
dp[0] = 0;
// State transition
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// The smaller value between not choosing and choosing coin i
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
public static void main(String[] args) {
int[] coins = { 1, 2, 5 };
int amt = 4;
// Dynamic programming
int res = coinChangeDP(coins, amt);
System.out.println("The minimum number of coins required to make up the target amount is " + res);
// Space-optimized dynamic programming
res = coinChangeDPComp(coins, amt);
System.out.println("The minimum number of coins required to make up the target amount is " + res);
}
}

View File

@@ -0,0 +1,67 @@
/**
* File: coin_change_ii.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class coin_change_ii {
/* Coin change II: Dynamic programming */
static int coinChangeIIDP(int[] coins, int amt) {
int n = coins.length;
// Initialize dp table
int[][] dp = new int[n + 1][amt + 1];
// Initialize first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transition
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// The sum of the two options of not choosing and choosing coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: Space-optimized dynamic programming */
static int coinChangeIIDPComp(int[] coins, int amt) {
int n = coins.length;
// Initialize dp table
int[] dp = new int[amt + 1];
dp[0] = 1;
// State transition
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If exceeding the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// The sum of the two options of not choosing and choosing coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
public static void main(String[] args) {
int[] coins = { 1, 2, 5 };
int amt = 5;
// Dynamic programming
int res = coinChangeIIDP(coins, amt);
System.out.println("The number of coin combinations to make up the target amount is " + res);
// Space-optimized dynamic programming
res = coinChangeIIDPComp(coins, amt);
System.out.println("The number of coin combinations to make up the target amount is " + res);
}
}

View File

@@ -0,0 +1,139 @@
/**
* File: edit_distance.java
* Created Time: 2023-07-13
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class edit_distance {
/* Edit distance: Brute force search */
static int editDistanceDFS(String s, String t, int i, int j) {
// If both s and t are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return the length of t
if (i == 0)
return j;
// If t is empty, return the length of s
if (j == 0)
return i;
// If the two characters are equal, skip these two characters
if (s.charAt(i - 1) == t.charAt(j - 1))
return editDistanceDFS(s, t, i - 1, j - 1);
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
int insert = editDistanceDFS(s, t, i, j - 1);
int delete = editDistanceDFS(s, t, i - 1, j);
int replace = editDistanceDFS(s, t, i - 1, j - 1);
// Return the minimum number of edits
return Math.min(Math.min(insert, delete), replace) + 1;
}
/* Edit distance: Memoized search */
static int editDistanceDFSMem(String s, String t, int[][] mem, int i, int j) {
// If both s and t are empty, return 0
if (i == 0 && j == 0)
return 0;
// If s is empty, return the length of t
if (i == 0)
return j;
// If t is empty, return the length of s
if (j == 0)
return i;
// If there is a record, return it
if (mem[i][j] != -1)
return mem[i][j];
// If the two characters are equal, skip these two characters
if (s.charAt(i - 1) == t.charAt(j - 1))
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
int delete = editDistanceDFSMem(s, t, mem, i - 1, j);
int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// Record and return the minimum number of edits
mem[i][j] = Math.min(Math.min(insert, delete), replace) + 1;
return mem[i][j];
}
/* Edit distance: Dynamic programming */
static int editDistanceDP(String s, String t) {
int n = s.length(), m = t.length();
int[][] dp = new int[n + 1][m + 1];
// State transition: first row and first column
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// State transition: the rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
// If the two characters are equal, skip these two characters
dp[i][j] = dp[i - 1][j - 1];
} else {
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
}
return dp[n][m];
}
/* Edit distance: Space-optimized dynamic programming */
static int editDistanceDPComp(String s, String t) {
int n = s.length(), m = t.length();
int[] dp = new int[m + 1];
// State transition: first row
for (int j = 1; j <= m; j++) {
dp[j] = j;
}
// State transition: the rest of the rows
for (int i = 1; i <= n; i++) {
// State transition: first column
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
dp[0] = i;
// State transition: the rest of the columns
for (int j = 1; j <= m; j++) {
int temp = dp[j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
// If the two characters are equal, skip these two characters
dp[j] = leftup;
} else {
// The minimum number of edits = the minimum number of edits from three operations (insert, remove, replace) + 1
dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), leftup) + 1;
}
leftup = temp; // Update for the next round of dp[i-1, j-1]
}
}
return dp[m];
}
public static void main(String[] args) {
String s = "bag";
String t = "pack";
int n = s.length(), m = t.length();
// Brute force search
int res = editDistanceDFS(s, t, n, m);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
// Memoized search
int[][] mem = new int[n + 1][m + 1];
for (int[] row : mem)
Arrays.fill(row, -1);
res = editDistanceDFSMem(s, t, mem, n, m);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
// Dynamic programming
res = editDistanceDP(s, t);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
// Space-optimized dynamic programming
res = editDistanceDPComp(s, t);
System.out.println("Changing " + s + " to " + t + " requires a minimum of " + res + " edits");
}
}

View File

@@ -0,0 +1,116 @@
/**
* File: knapsack.java
* Created Time: 2023-07-10
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class knapsack {
/* 0-1 Knapsack: Brute force search */
static int knapsackDFS(int[] wgt, int[] val, int i, int c) {
// If all items have been chosen or the knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If exceeding the knapsack capacity, can only choose not to put it in the knapsack
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, val, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
int no = knapsackDFS(wgt, val, i - 1, c);
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// Return the greater value of the two options
return Math.max(no, yes);
}
/* 0-1 Knapsack: Memoized search */
static int knapsackDFSMem(int[] wgt, int[] val, int[][] mem, int i, int c) {
// If all items have been chosen or the knapsack has no remaining capacity, return value 0
if (i == 0 || c == 0) {
return 0;
}
// If there is a record, return it
if (mem[i][c] != -1) {
return mem[i][c];
}
// If exceeding the knapsack capacity, can only choose not to put it in the knapsack
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, val, mem, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
int yes = knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// Record and return the greater value of the two options
mem[i][c] = Math.max(no, yes);
return mem[i][c];
}
/* 0-1 Knapsack: Dynamic programming */
static int knapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
int[][] dp = new int[n + 1][cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
dp[i][c] = dp[i - 1][c];
} else {
// The greater value between not choosing and choosing item i
dp[i][c] = Math.max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* 0-1 Knapsack: Space-optimized dynamic programming */
static int knapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
int[] dp = new int[cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
// Traverse in reverse order
for (int c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// The greater value between not choosing and choosing item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
public static void main(String[] args) {
int[] wgt = { 10, 20, 30, 40, 50 };
int[] val = { 50, 120, 150, 210, 240 };
int cap = 50;
int n = wgt.length;
// Brute force search
int res = knapsackDFS(wgt, val, n, cap);
System.out.println("The maximum value within the bag capacity is " + res);
// Memoized search
int[][] mem = new int[n + 1][cap + 1];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = knapsackDFSMem(wgt, val, mem, n, cap);
System.out.println("The maximum value within the bag capacity is " + res);
// Dynamic programming
res = knapsackDP(wgt, val, cap);
System.out.println("The maximum value within the bag capacity is " + res);
// Space-optimized dynamic programming
res = knapsackDPComp(wgt, val, cap);
System.out.println("The maximum value within the bag capacity is " + res);
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: min_cost_climbing_stairs_dp.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class min_cost_climbing_stairs_dp {
/* Climbing stairs with minimum cost: Dynamic programming */
public static int minCostClimbingStairsDP(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
return cost[n];
// Initialize dp table, used to store subproblem solutions
int[] dp = new int[n + 1];
// Initial state: preset the smallest subproblem solution
dp[1] = cost[1];
dp[2] = cost[2];
// State transition: gradually solve larger subproblems from smaller ones
for (int i = 3; i <= n; i++) {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* Climbing stairs with minimum cost: Space-optimized dynamic programming */
public static int minCostClimbingStairsDPComp(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
return cost[n];
int a = cost[1], b = cost[2];
for (int i = 3; i <= n; i++) {
int tmp = b;
b = Math.min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
public static void main(String[] args) {
int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
System.out.println(String.format("Input the cost list for stairs as %s", Arrays.toString(cost)));
int res = minCostClimbingStairsDP(cost);
System.out.println(String.format("Minimum cost to climb the stairs %d", res));
res = minCostClimbingStairsDPComp(cost);
System.out.println(String.format("Minimum cost to climb the stairs %d", res));
}
}

View File

@@ -0,0 +1,125 @@
/**
* File: min_path_sum.java
* Created Time: 2023-07-10
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class min_path_sum {
/* Minimum path sum: Brute force search */
static int minPathSumDFS(int[][] grid, int i, int j) {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0];
}
// If the row or column index is out of bounds, return a +∞ cost
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// Calculate the minimum path cost from the top-left to (i-1, j) and (i, j-1)
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// Return the minimum path cost from the top-left to (i, j)
return Math.min(left, up) + grid[i][j];
}
/* Minimum path sum: Memoized search */
static int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
// If it's the top-left cell, terminate the search
if (i == 0 && j == 0) {
return grid[0][0];
}
// If the row or column index is out of bounds, return a +∞ cost
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// If there is a record, return it
if (mem[i][j] != -1) {
return mem[i][j];
}
// The minimum path cost from the left and top cells
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// Record and return the minimum path cost from the top-left to (i, j)
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* Minimum path sum: Dynamic programming */
static int minPathSumDP(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize dp table
int[][] dp = new int[n][m];
dp[0][0] = grid[0][0];
// State transition: first row
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// State transition: first column
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// State transition: the rest of the rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* Minimum path sum: Space-optimized dynamic programming */
static int minPathSumDPComp(int[][] grid) {
int n = grid.length, m = grid[0].length;
// Initialize dp table
int[] dp = new int[m];
// State transition: first row
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transition: the rest of the rows
for (int i = 1; i < n; i++) {
// State transition: first column
dp[0] = dp[0] + grid[i][0];
// State transition: the rest of the columns
for (int j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
public static void main(String[] args) {
int[][] grid = {
{ 1, 3, 1, 5 },
{ 2, 2, 4, 2 },
{ 5, 3, 2, 1 },
{ 4, 3, 5, 2 }
};
int n = grid.length, m = grid[0].length;
// Brute force search
int res = minPathSumDFS(grid, n - 1, m - 1);
System.out.println("The minimum path sum from the top left corner to the bottom right corner is " + res);
// Memoized search
int[][] mem = new int[n][m];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
System.out.println("The minimum path sum from the top left corner to the bottom right corner is " + res);
// Dynamic programming
res = minPathSumDP(grid);
System.out.println("The minimum path sum from the top left corner to the bottom right corner is " + res);
// Space-optimized dynamic programming
res = minPathSumDPComp(grid);
System.out.println("The minimum path sum from the top left corner to the bottom right corner is " + res);
}
}

View File

@@ -0,0 +1,63 @@
/**
* File: unbounded_knapsack.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class unbounded_knapsack {
/* Complete knapsack: Dynamic programming */
static int unboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
int[][] dp = new int[n + 1][cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
dp[i][c] = dp[i - 1][c];
} else {
// The greater value between not choosing and choosing item i
dp[i][c] = Math.max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* Complete knapsack: Space-optimized dynamic programming */
static int unboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize dp table
int[] dp = new int[cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If exceeding the knapsack capacity, do not choose item i
dp[c] = dp[c];
} else {
// The greater value between not choosing and choosing item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
public static void main(String[] args) {
int[] wgt = { 1, 2, 3 };
int[] val = { 5, 11, 15 };
int cap = 4;
// Dynamic programming
int res = unboundedKnapsackDP(wgt, val, cap);
System.out.println("The maximum value within the bag capacity is " + res);
// Space-optimized dynamic programming
res = unboundedKnapsackDPComp(wgt, val, cap);
System.out.println("The maximum value within the bag capacity is " + res);
}
}