mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-02 18:20:58 +08:00
Add the initial EN translation for C++ code (#1346)
This commit is contained in:
10
en/codes/cpp/chapter_dynamic_programming/CMakeLists.txt
Normal file
10
en/codes/cpp/chapter_dynamic_programming/CMakeLists.txt
Normal file
@@ -0,0 +1,10 @@
|
||||
add_executable(climbing_stairs_backtrack climbing_stairs_backtrack.cpp)
|
||||
add_executable(climbing_stairs_dfs climbing_stairs_dfs.cpp)
|
||||
add_executable(climbing_stairs_dfs_mem climbing_stairs_dfs_mem.cpp)
|
||||
add_executable(climbing_stairs_dp climbing_stairs_dp.cpp)
|
||||
add_executable(min_cost_climbing_stairs_dp min_cost_climbing_stairs_dp.cpp)
|
||||
add_executable(min_path_sum min_path_sum.cpp)
|
||||
add_executable(unbounded_knapsack unbounded_knapsack.cpp)
|
||||
add_executable(coin_change coin_change.cpp)
|
||||
add_executable(coin_change_ii coin_change_ii.cpp)
|
||||
add_executable(edit_distance edit_distance.cpp)
|
||||
@@ -0,0 +1,43 @@
|
||||
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.cpp
|
||||
* Created Time: 2023-06-30
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Backtracking */
|
||||
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
|
||||
// When climbing to the nth step, add 1 to the number of solutions
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// Traverse all choices
|
||||
for (auto &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 */
|
||||
int climbingStairsBacktrack(int n) {
|
||||
vector<int> choices = {1, 2}; // Can choose to climb up 1 step or 2 steps
|
||||
int state = 0; // Start climbing from the 0th step
|
||||
vector<int> res = {0}; // Use res[0] to record the number of solutions
|
||||
backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsBacktrack(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.cpp
|
||||
* Created Time: 2023-07-01
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Constrained climbing stairs: Dynamic programming */
|
||||
int climbingStairsConstraintDP(int n) {
|
||||
if (n == 1 || n == 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store subproblem solutions
|
||||
vector<vector<int>> dp(n + 1, vector<int>(3, 0));
|
||||
// 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];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsConstraintDP(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.cpp
|
||||
* Created Time: 2023-06-30
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Search */
|
||||
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 */
|
||||
int climbingStairsDFS(int n) {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFS(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.cpp
|
||||
* Created Time: 2023-06-30
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Memoized search */
|
||||
int dfs(int i, vector<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 */
|
||||
int climbingStairsDFSMem(int n) {
|
||||
// mem[i] records the total number of solutions for climbing to the ith step, -1 means no record
|
||||
vector<int> mem(n + 1, -1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDFSMem(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.cpp
|
||||
* Created Time: 2023-06-30
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
int climbingStairsDP(int n) {
|
||||
if (n == 1 || n == 2)
|
||||
return n;
|
||||
// Initialize dp table, used to store subproblem solutions
|
||||
vector<int> dp(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 */
|
||||
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;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
int n = 9;
|
||||
|
||||
int res = climbingStairsDP(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
res = climbingStairsDPComp(n);
|
||||
cout << "There are " << res << " solutions to climb " << n << " stairs" << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
70
en/codes/cpp/chapter_dynamic_programming/coin_change.cpp
Normal file
70
en/codes/cpp/chapter_dynamic_programming/coin_change.cpp
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* File: coin_change.cpp
|
||||
* Created Time: 2023-07-11
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
int coinChangeDP(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
||||
// 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] = 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 */
|
||||
int coinChangeDPComp(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
int MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
vector<int> dp(amt + 1, 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] = min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] != MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> coins = {1, 2, 5};
|
||||
int amt = 4;
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeDP(coins, amt);
|
||||
cout << "The minimum number of coins required to make up the target amount is " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
cout << "The minimum number of coins required to make up the target amount is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
68
en/codes/cpp/chapter_dynamic_programming/coin_change_ii.cpp
Normal file
68
en/codes/cpp/chapter_dynamic_programming/coin_change_ii.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: coin_change_ii.cpp
|
||||
* Created Time: 2023-07-11
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
int coinChangeIIDP(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
// Initialize dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
||||
// 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 */
|
||||
int coinChangeIIDPComp(vector<int> &coins, int amt) {
|
||||
int n = coins.size();
|
||||
// Initialize dp table
|
||||
vector<int> dp(amt + 1, 0);
|
||||
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];
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> coins = {1, 2, 5};
|
||||
int amt = 5;
|
||||
|
||||
// Dynamic programming
|
||||
int res = coinChangeIIDP(coins, amt);
|
||||
cout << "The number of coin combinations to make up the target amount is " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
cout << "The number of coin combinations to make up the target amount is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
136
en/codes/cpp/chapter_dynamic_programming/edit_distance.cpp
Normal file
136
en/codes/cpp/chapter_dynamic_programming/edit_distance.cpp
Normal file
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* File: edit_distance.cpp
|
||||
* Created Time: 2023-07-13
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Edit distance: Brute force search */
|
||||
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[i - 1] == t[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 del = editDistanceDFS(s, t, i - 1, j);
|
||||
int replace = editDistanceDFS(s, t, i - 1, j - 1);
|
||||
// Return the minimum number of edits
|
||||
return min(min(insert, del), replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoized search */
|
||||
int editDistanceDFSMem(string s, string t, vector<vector<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[i - 1] == t[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 del = 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] = min(min(insert, del), replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
int editDistanceDP(string s, string t) {
|
||||
int n = s.length(), m = t.length();
|
||||
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
|
||||
// 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[i - 1] == t[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] = min(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 */
|
||||
int editDistanceDPComp(string s, string t) {
|
||||
int n = s.length(), m = t.length();
|
||||
vector<int> dp(m + 1, 0);
|
||||
// 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[i - 1] == t[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] = min(min(dp[j - 1], dp[j]), leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for the next round of dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
string s = "bag";
|
||||
string t = "pack";
|
||||
int n = s.length(), m = t.length();
|
||||
|
||||
// Brute force search
|
||||
int res = editDistanceDFS(s, t, n, m);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
|
||||
|
||||
// Memoized search
|
||||
vector<vector<int>> mem(n + 1, vector<int>(m + 1, -1));
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
cout << "Changing " << s << " to " << t << " requires a minimum of " << res << " edits.\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
109
en/codes/cpp/chapter_dynamic_programming/knapsack.cpp
Normal file
109
en/codes/cpp/chapter_dynamic_programming/knapsack.cpp
Normal file
@@ -0,0 +1,109 @@
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
/* 0-1 Knapsack: Brute force search */
|
||||
int knapsackDFS(vector<int> &wgt, vector<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 max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 Knapsack: Memoized search */
|
||||
int knapsackDFSMem(vector<int> &wgt, vector<int> &val, vector<vector<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] = max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 Knapsack: Dynamic programming */
|
||||
int knapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
int n = wgt.size();
|
||||
// Initialize dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
|
||||
// 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] = 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 */
|
||||
int knapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
int n = wgt.size();
|
||||
// Initialize dp table
|
||||
vector<int> dp(cap + 1, 0);
|
||||
// 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] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
vector<int> wgt = {10, 20, 30, 40, 50};
|
||||
vector<int> val = {50, 120, 150, 210, 240};
|
||||
int cap = 50;
|
||||
int n = wgt.size();
|
||||
|
||||
// Brute force search
|
||||
int res = knapsackDFS(wgt, val, n, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
// Memoized search
|
||||
vector<vector<int>> mem(n + 1, vector<int>(cap + 1, -1));
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.cpp
|
||||
* Created Time: 2023-06-30
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Climbing stairs with minimum cost: Dynamic programming */
|
||||
int minCostClimbingStairsDP(vector<int> &cost) {
|
||||
int n = cost.size() - 1;
|
||||
if (n == 1 || n == 2)
|
||||
return cost[n];
|
||||
// Initialize dp table, used to store subproblem solutions
|
||||
vector<int> dp(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] = min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs with minimum cost: Space-optimized dynamic programming */
|
||||
int minCostClimbingStairsDPComp(vector<int> &cost) {
|
||||
int n = cost.size() - 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 = min(a, tmp) + cost[i];
|
||||
a = tmp;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
vector<int> cost = {0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1};
|
||||
cout << "Input the cost list for stairs";
|
||||
printVector(cost);
|
||||
|
||||
int res = minCostClimbingStairsDP(cost);
|
||||
cout << "Minimum cost to climb the stairs " << res << endl;
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
cout << "Minimum cost to climb the stairs " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
116
en/codes/cpp/chapter_dynamic_programming/min_path_sum.cpp
Normal file
116
en/codes/cpp/chapter_dynamic_programming/min_path_sum.cpp
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* File: min_path_sum.cpp
|
||||
* Created Time: 2023-07-10
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Minimum path sum: Brute force search */
|
||||
int minPathSumDFS(vector<vector<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 INT_MAX;
|
||||
}
|
||||
// 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 min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoized search */
|
||||
int minPathSumDFSMem(vector<vector<int>> &grid, vector<vector<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 INT_MAX;
|
||||
}
|
||||
// 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] = min(left, up) != INT_MAX ? min(left, up) + grid[i][j] : INT_MAX;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
int minPathSumDP(vector<vector<int>> &grid) {
|
||||
int n = grid.size(), m = grid[0].size();
|
||||
// Initialize dp table
|
||||
vector<vector<int>> dp(n, vector<int>(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] = 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 */
|
||||
int minPathSumDPComp(vector<vector<int>> &grid) {
|
||||
int n = grid.size(), m = grid[0].size();
|
||||
// Initialize dp table
|
||||
vector<int> dp(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] = min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
int main() {
|
||||
vector<vector<int>> grid = {{1, 3, 1, 5}, {2, 2, 4, 2}, {5, 3, 2, 1}, {4, 3, 5, 2}};
|
||||
int n = grid.size(), m = grid[0].size();
|
||||
|
||||
// Brute force search
|
||||
int res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
|
||||
|
||||
// Memoized search
|
||||
vector<vector<int>> mem(n, vector<int>(m, -1));
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
cout << "The minimum path sum from the top left corner to the bottom right corner is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.cpp
|
||||
* Created Time: 2023-07-11
|
||||
* Author: krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
#include "../utils/common.hpp"
|
||||
|
||||
/* Complete knapsack: Dynamic programming */
|
||||
int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
int n = wgt.size();
|
||||
// Initialize dp table
|
||||
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
|
||||
// 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] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Complete knapsack: Space-optimized dynamic programming */
|
||||
int unboundedKnapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
|
||||
int n = wgt.size();
|
||||
// Initialize dp table
|
||||
vector<int> dp(cap + 1, 0);
|
||||
// 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] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver code */
|
||||
int main() {
|
||||
vector<int> wgt = {1, 2, 3};
|
||||
vector<int> val = {5, 11, 15};
|
||||
int cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
int res = unboundedKnapsackDP(wgt, val, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
cout << "The maximum value within the bag capacity is " << res << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user