feat: add the section of the introduction to dynamic programming (#571)

* add the section of the introduction to
dynamic programming

* add a code comments.
This commit is contained in:
Yudong Jin
2023-06-30 04:31:43 +08:00
committed by GitHub
parent 4722e7bca7
commit 3f03663d2e
28 changed files with 1268 additions and 4 deletions

View File

@ -15,3 +15,4 @@ add_subdirectory(chapter_graph)
add_subdirectory(chapter_sorting)
add_subdirectory(chapter_searching)
add_subdirectory(chapter_backtracking)
add_subdirectory(chapter_dynamic_programming)

View File

@ -0,0 +1,5 @@
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)

View File

@ -0,0 +1,43 @@
/**
* File: climbing_stairs_backtrack.cpp
* Created Time: 2023-06-30
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 回溯 */
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
// 当爬到第 n 阶时,方案数量加 1
if (state == n)
res[0]++;
// 遍历所有选择
for (auto &choice : choices) {
// 剪枝:不允许越过第 n 阶
if (state + choice > n)
break;
// 尝试:做出选择,更新状态
backtrack(choices, state + choice, n, res);
// 回退
}
}
/* 爬楼梯:回溯 */
int climbingStairsBacktrack(int n) {
vector<int> choices = {1, 2}; // 可选择向上爬 1 或 2 阶
int state = 0; // 从第 0 阶开始爬
vector<int> res = {0}; // 使用 res[0] 记录方案数量
backtrack(choices, state, n, res);
return res[0];
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
cout << "" << n << " 阶楼梯共有 " << res << " 种方案" << endl;
return 0;
}

View File

@ -0,0 +1,32 @@
/**
* File: climbing_stairs_dfs.cpp
* Created Time: 2023-06-30
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 搜索 */
int dfs(int i) {
// 已知 dp[1] 和 dp[2] ,返回之
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;
}
/* 爬楼梯:搜索 */
int climbingStairsDFS(int n) {
return dfs(n);
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsDFS(n);
cout << "" << n << " 阶楼梯共有 " << res << " 种方案" << endl;
return 0;
}

View File

@ -0,0 +1,39 @@
/**
* File: climbing_stairs_dfs_mem.cpp
* Created Time: 2023-06-30
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 记忆化搜索 */
int dfs(int i, vector<int> &mem) {
// 已知 dp[1] 和 dp[2] ,返回之
if (i == 1 || i == 2)
return i;
// 若存在记录 dp[i] ,则直接返回之
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);
// 记录 dp[i]
mem[i] = count;
return count;
}
/* 爬楼梯:记忆化搜索 */
int climbingStairsDFSMem(int n) {
// mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录
vector<int> mem(n + 1, -1);
return dfs(n, mem);
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsDFSMem(n);
cout << "" << n << " 阶楼梯共有 " << res << " 种方案" << endl;
return 0;
}

View File

@ -0,0 +1,49 @@
/**
* File: climbing_stairs_dp.cpp
* Created Time: 2023-06-30
* Author: Krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* 爬楼梯:动态规划 */
int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// 初始化 dp 列表,用于存储子问题的解
vector<int> dp(n + 1);
// 初始状态:预设最小子问题的解
dp[1] = 1;
dp[2] = 2;
// 状态转移:从较小子问题逐步求解较大子问题
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* 爬楼梯:状态压缩后的动态规划 */
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 << "" << n << " 阶楼梯共有 " << res << " 种方案" << endl;
res = climbingStairsDPComp(n);
cout << "" << n << " 阶楼梯共有 " << res << " 种方案" << endl;
return 0;
}

View File

@ -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"
/* 爬楼梯最小代价:动态规划 */
int minCostClimbingStairsDP(vector<int> &cost) {
int n = cost.size() - 1;
if (n == 1 || n == 2)
return cost[n];
// 初始化 dp 列表,用于存储子问题的解
vector<int> dp(n + 1);
// 初始状态:预设最小子问题的解
dp[1] = cost[1];
dp[2] = cost[2];
// 状态转移:从较小子问题逐步求解较大子问题
for (int i = 3; i <= n; i++) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* 爬楼梯最小代价:状态压缩后的动态规划 */
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 << "输入楼梯的代价列表为 ";
printVector(cost);
int res = minCostClimbingStairsDP(cost);
cout << "爬完楼梯的最低代价为 " << res << endl;
res = minCostClimbingStairsDPComp(cost);
cout << "爬完楼梯的最低代价为 " << res << endl;
return 0;
}

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 {
/* 回溯 */
public static void backtrack(List<Integer> choices, int state, int n, List<Integer> res) {
// 当爬到第 n 阶时,方案数量加 1
if (state == n)
res.set(0, res.get(0) + 1);
// 遍历所有选择
for (Integer choice : choices) {
// 剪枝:不允许越过第 n 阶
if (state + choice > n)
break;
// 尝试:做出选择,更新状态
backtrack(choices, state + choice, n, res);
// 回退
}
}
/* 爬楼梯:回溯 */
public static int climbingStairsBacktrack(int n) {
List<Integer> choices = Arrays.asList(1, 2); // 可选择向上爬 1 或 2 阶
int state = 0; // 从第 0 阶开始爬
List<Integer> res = new ArrayList<>();
res.add(0); // 使用 res[0] 记录方案数量
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("爬 %d 阶楼梯共有 %d 种方案", 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 {
/* 搜索 */
public static int dfs(int i) {
// 已知 dp[1] 和 dp[2] ,返回之
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;
}
/* 爬楼梯:搜索 */
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("爬 %d 阶楼梯共有 %d 种方案", 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 {
/* 记忆化搜索 */
public static int dfs(int i, int[] mem) {
// 已知 dp[1] 和 dp[2] ,返回之
if (i == 1 || i == 2)
return i;
// 若存在记录 dp[i] ,则直接返回之
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);
// 记录 dp[i]
mem[i] = count;
return count;
}
/* 爬楼梯:记忆化搜索 */
public static int climbingStairsDFSMem(int n) {
// mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录
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("爬 %d 阶楼梯共有 %d 种方案", 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 {
/* 爬楼梯:动态规划 */
public static int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// 初始化 dp 列表,用于存储子问题的解
int[] dp = new int[n + 1];
// 初始状态:预设最小子问题的解
dp[1] = 1;
dp[2] = 2;
// 状态转移:从较小子问题逐步求解较大子问题
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* 爬楼梯:状态压缩后的动态规划 */
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("爬 %d 阶楼梯共有 %d 种方案", n, res));
res = climbingStairsDPComp(n);
System.out.println(String.format("爬 %d 阶楼梯共有 %d 种方案", n, 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 {
/* 爬楼梯最小代价:动态规划 */
public static int minCostClimbingStairsDP(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
return cost[n];
// 初始化 dp 列表,用于存储子问题的解
int[] dp = new int[n + 1];
// 初始状态:预设最小子问题的解
dp[1] = cost[1];
dp[2] = cost[2];
// 状态转移:从较小子问题逐步求解较大子问题
for (int i = 3; i <= n; i++) {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* 爬楼梯最小代价:状态压缩后的动态规划 */
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("输入楼梯的代价列表为 %s", Arrays.toString(cost)));
int res = minCostClimbingStairsDP(cost);
System.out.println(String.format("爬完楼梯的最低代价为 %d", res));
res = minCostClimbingStairsDPComp(cost);
System.out.println(String.format("爬完楼梯的最低代价为 %d", res));
}
}

View File

@ -0,0 +1,37 @@
"""
File: climbing_stairs_backtrack.py
Created Time: 2023-06-30
Author: Krahets (krahets@163.com)
"""
def backtrack(choices: list[int], state: int, n: int, res: list[int]) -> int:
"""回溯"""
# 当爬到第 n 阶时,方案数量加 1
if state == n:
res[0] += 1
# 遍历所有选择
for choice in choices:
# 剪枝:不允许越过第 n 阶
if state + choice > n:
break
# 尝试:做出选择,更新状态
backtrack(choices, state + choice, n, res)
# 回退
def climbing_stairs_backtrack(n: int) -> int:
"""爬楼梯:回溯"""
choices = [1, 2] # 可选择向上爬 1 或 2 阶
state = 0 # 从第 0 阶开始爬
res = [0] # 使用 res[0] 记录方案数量
backtrack(choices, state, n, res)
return res[0]
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_backtrack(n)
print(f"{n} 阶楼梯共有 {res} 种方案")

View File

@ -0,0 +1,28 @@
"""
File: climbing_stairs_dfs.py
Created Time: 2023-06-30
Author: Krahets (krahets@163.com)
"""
def dfs(i: int) -> int:
"""搜索"""
# 已知 dp[1] 和 dp[2] ,返回之
if i == 1 or i == 2:
return i
# dp[i] = dp[i-1] + dp[i-2]
count = dfs(i - 1) + dfs(i - 2)
return count
def climbing_stairs_dfs(n: int) -> int:
"""爬楼梯:搜索"""
return dfs(n)
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dfs(n)
print(f"{n} 阶楼梯共有 {res} 种方案")

View File

@ -0,0 +1,35 @@
"""
File: climbing_stairs_dfs_mem.py
Created Time: 2023-06-30
Author: Krahets (krahets@163.com)
"""
def dfs(i: int, mem: list[int]) -> int:
"""记忆化搜索"""
# 已知 dp[1] 和 dp[2] ,返回之
if i == 1 or i == 2:
return i
# 若存在记录 dp[i] ,则直接返回之
if mem[i] != -1:
return mem[i]
# dp[i] = dp[i-1] + dp[i-2]
count = dfs(i - 1, mem) + dfs(i - 2, mem)
# 记录 dp[i]
mem[i] = count
return count
def climbing_stairs_dfs_mem(n: int) -> int:
"""爬楼梯:记忆化搜索"""
# mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录
mem = [-1] * (n + 1)
return dfs(n, mem)
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dfs_mem(n)
print(f"{n} 阶楼梯共有 {res} 种方案")

View File

@ -0,0 +1,40 @@
"""
File: climbing_stairs_dp.py
Created Time: 2023-06-30
Author: Krahets (krahets@163.com)
"""
def climbing_stairs_dp(n: int) -> int:
"""爬楼梯:动态规划"""
if n == 1 or n == 2:
return n
# 初始化 dp 列表,用于存储子问题的解
dp = [0] * (n + 1)
# 初始状态:预设最小子问题的解
dp[1], dp[2] = 1, 2
# 状态转移:从较小子问题逐步求解较大子问题
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
def climbing_stairs_dp_comp(n: int) -> int:
"""爬楼梯:状态压缩后的动态规划"""
if n == 1 or n == 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
"""Driver Code"""
if __name__ == "__main__":
n = 9
res = climbing_stairs_dp(n)
print(f"{n} 阶楼梯共有 {res} 种方案")
res = climbing_stairs_dp_comp(n)
print(f"{n} 阶楼梯共有 {res} 种方案")

View File

@ -0,0 +1,43 @@
"""
File: min_cost_climbing_stairs_dp.py
Created Time: 2023-06-30
Author: Krahets (krahets@163.com)
"""
def min_cost_climbing_stairs_dp(cost: list[int]) -> int:
"""爬楼梯最小代价:动态规划"""
n = len(cost) - 1
if n == 1 or n == 2:
return cost[n]
# 初始化 dp 列表,用于存储子问题的解
dp = [0] * (n + 1)
# 初始状态:预设最小子问题的解
dp[1], dp[2] = cost[1], cost[2]
# 状态转移:从较小子问题逐步求解较大子问题
for i in range(3, n + 1):
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
return dp[n]
def min_cost_climbing_stairs_dp_comp(cost: list[int]) -> int:
"""爬楼梯最小代价:状态压缩后的动态规划"""
n = len(cost) - 1
if n == 1 or n == 2:
return cost[n]
a, b = cost[1], cost[2]
for i in range(3, n + 1):
a, b = b, min(a, b) + cost[i]
return b
"""Driver Code"""
if __name__ == "__main__":
cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1]
print(f"输入楼梯的代价列表为 {cost}")
res = min_cost_climbing_stairs_dp(cost)
print(f"爬完楼梯的最低代价为 {res}")
res = min_cost_climbing_stairs_dp_comp(cost)
print(f"爬完楼梯的最低代价为 {res}")