diff --git a/chapter_computational_complexity/iteration_and_recursion.md b/chapter_computational_complexity/iteration_and_recursion.md index 34c9373bc..f39c35dd7 100644 --- a/chapter_computational_complexity/iteration_and_recursion.md +++ b/chapter_computational_complexity/iteration_and_recursion.md @@ -1568,7 +1568,24 @@ status: new === "Dart" ```dart title="recursion.dart" - [class]{}-[func]{forLoopRecur} + /* 使用迭代模拟递归 */ + int forLoopRecur(int n) { + // 使用一个显式的栈来模拟系统调用栈 + List stack = []; + int res = 0; + // 递:递归调用 + for (int i = n; i > 0; i--) { + // 通过“入栈操作”模拟“递” + stack.add(i); + } + // 归:返回结果 + while (!stack.isEmpty) { + // 通过“出栈操作”模拟“归” + res += stack.removeLast(); + } + // res = 1+2+3+...+n + return res; + } ``` === "Rust" diff --git a/chapter_dynamic_programming/intro_to_dynamic_programming.md b/chapter_dynamic_programming/intro_to_dynamic_programming.md index 2f821e77c..4ddef50b7 100644 --- a/chapter_dynamic_programming/intro_to_dynamic_programming.md +++ b/chapter_dynamic_programming/intro_to_dynamic_programming.md @@ -321,9 +321,35 @@ comments: true === "C" ```c title="climbing_stairs_backtrack.c" - [class]{}-[func]{backtrack} + /* 回溯 */ + void backtrack(int *choices, int state, int n, int *res, int len) { + // 当爬到第 n 阶时,方案数量加 1 + if (state == n) + res[0]++; + // 遍历所有选择 + for (int i = 0; i < len; i++) { + int choice = choices[i]; + // 剪枝:不允许越过第 n 阶 + if (state + choice > n) + break; + // 尝试:做出选择,更新状态 + backtrack(choices, state + choice, n, res, len); + // 回退 + } + } - [class]{}-[func]{climbingStairsBacktrack} + /* 爬楼梯:回溯 */ + int climbingStairsBacktrack(int n) { + int choices[2] = {1, 2}; // 可选择向上爬 1 或 2 阶 + int state = 0; // 从第 0 阶开始爬 + int *res = (int *)malloc(sizeof(int)); + *res = 0; // 使用 res[0] 记录方案数量 + int len = sizeof(choices) / sizeof(int); + backtrack(choices, state, n, res, len); + int result = *res; + free(res); + return result; + } ``` === "Zig" @@ -576,9 +602,20 @@ $$ === "C" ```c title="climbing_stairs_dfs.c" - [class]{}-[func]{dfs} + /* 搜索 */ + 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; + } - [class]{}-[func]{climbingStairsDFS} + /* 爬楼梯:搜索 */ + int climbingStairsDFS(int n) { + return dfs(n); + } ``` === "Zig" @@ -880,9 +917,32 @@ $$ === "C" ```c title="climbing_stairs_dfs_mem.c" - [class]{}-[func]{dfs} + /* 记忆化搜索 */ + 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; + } - [class]{}-[func]{climbingStairsDFSMem} + /* 爬楼梯:记忆化搜索 */ + int climbingStairsDFSMem(int n) { + // mem[i] 记录爬到第 i 阶的方案总数,-1 代表无记录 + int *mem = (int *)malloc((n + 1) * sizeof(int)); + for (int i = 0; i <= n; i++) { + mem[i] = -1; + } + int result = dfs(n, mem); + free(mem); + return result; + } ``` === "Zig" @@ -1126,7 +1186,23 @@ $$ === "C" ```c title="climbing_stairs_dp.c" - [class]{}-[func]{climbingStairsDP} + /* 爬楼梯:动态规划 */ + int climbingStairsDP(int n) { + if (n == 1 || n == 2) + return n; + // 初始化 dp 表,用于存储子问题的解 + int *dp = (int *)malloc((n + 1) * sizeof(int)); + // 初始状态:预设最小子问题的解 + dp[1] = 1; + dp[2] = 2; + // 状态转移:从较小子问题逐步求解较大子问题 + for (int i = 3; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + int result = dp[n]; + free(dp); + return result; + } ``` === "Zig" @@ -1336,7 +1412,18 @@ $$ === "C" ```c title="climbing_stairs_dp.c" - [class]{}-[func]{climbingStairsDPComp} + /* 爬楼梯:空间优化后的动态规划 */ + 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; + } ``` === "Zig" diff --git a/chapter_graph/graph_traversal.md b/chapter_graph/graph_traversal.md index 0b1fbf543..0d30b114d 100644 --- a/chapter_graph/graph_traversal.md +++ b/chapter_graph/graph_traversal.md @@ -6,7 +6,7 @@ comments: true 树代表的是“一对多”的关系,而图则具有更高的自由度,可以表示任意的“多对多”关系。因此,我们可以把树看作是图的一种特例。显然,**树的遍历操作也是图的遍历操作的一种特例**。 -图和树都都需要应用搜索算法来实现遍历操作。图的遍历方式可分为两种:「广度优先遍历 breadth-first traversal」和「深度优先遍历 depth-first traversal」。它们也常被称为「广度优先搜索 breadth-first search」和「深度优先搜索 depth-first search」,简称 BFS 和 DFS 。 +图和树都需要应用搜索算法来实现遍历操作。图的遍历方式可分为两种:「广度优先遍历 breadth-first traversal」和「深度优先遍历 depth-first traversal」。它们也常被称为「广度优先搜索 breadth-first search」和「深度优先搜索 depth-first search」,简称 BFS 和 DFS 。 ## 9.3.1   广度优先遍历 diff --git a/chapter_hashing/hash_collision.md b/chapter_hashing/hash_collision.md index 3af6ba4d7..5e57a1133 100644 --- a/chapter_hashing/hash_collision.md +++ b/chapter_hashing/hash_collision.md @@ -2392,20 +2392,16 @@ comments: true /* 开放寻址哈希表 */ class HashMapOpenAddressing { late int _size; // 键值对数量 - late int _capacity; // 哈希表容量 - late double _loadThres; // 触发扩容的负载因子阈值 - late int _extendRatio; // 扩容倍数 + int _capacity = 4; // 哈希表容量 + double _loadThres = 2.0 / 3.0; // 触发扩容的负载因子阈值 + int _extendRatio = 2; // 扩容倍数 late List _buckets; // 桶数组 - late Pair _removed; // 删除标记 + Pair _TOMBSTONE = Pair(-1, "-1"); // 删除标记 /* 构造方法 */ HashMapOpenAddressing() { _size = 0; - _capacity = 4; - _loadThres = 2.0 / 3.0; - _extendRatio = 2; _buckets = List.generate(_capacity, (index) => null); - _removed = Pair(-1, "-1"); } /* 哈希函数 */ @@ -2418,19 +2414,42 @@ comments: true return _size / _capacity; } + /* 搜索 key 对应的桶索引 */ + int findBucket(int key) { + int index = hashFunc(key); + int firstTombstone = -1; + // 线性探测,当遇到空桶时跳出 + while (_buckets[index] != null) { + // 若遇到 key ,返回对应桶索引 + if (_buckets[index]!.key == key) { + // 若之前遇到了删除标记,则将键值对移动至该索引 + if (firstTombstone != -1) { + _buckets[firstTombstone] = _buckets[index]; + _buckets[index] = _TOMBSTONE; + return firstTombstone; // 返回移动后的桶索引 + } + return index; // 返回桶索引 + } + // 记录遇到的首个删除标记 + if (firstTombstone == -1 && _buckets[index] == _TOMBSTONE) { + firstTombstone = index; + } + // 计算桶索引,越过尾部返回头部 + index = (index + 1) % _capacity; + } + // 若 key 不存在,则返回添加点的索引 + return firstTombstone == -1 ? index : firstTombstone; + } + /* 查询操作 */ String? get(int key) { - int index = hashFunc(key); - // 线性探测,从 index 开始向后遍历 - for (int i = 0; i < _capacity; i++) { - // 计算桶索引,越过尾部返回头部 - int j = (index + i) % _capacity; - // 若遇到空桶,说明无此 key ,则返回 null - if (_buckets[j] == null) return null; - // 若遇到指定 key ,则返回对应 val - if (_buckets[j]!.key == key && _buckets[j] != _removed) - return _buckets[j]!.val; + // 搜索 key 对应的桶索引 + int index = findBucket(key); + // 若找到键值对,则返回对应 val + if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) { + return _buckets[index]!.val; } + // 若键值对不存在,则返回 null return null; } @@ -2440,42 +2459,26 @@ comments: true if (loadFactor() > _loadThres) { extend(); } - int index = hashFunc(key); - // 线性探测,从 index 开始向后遍历 - for (int i = 0; i < _capacity; i++) { - // 计算桶索引,越过尾部返回头部 - int j = (index + i) % _capacity; - // 若遇到空桶、或带有删除标记的桶,则将键值对放入该桶 - if (_buckets[j] == null || _buckets[j] == _removed) { - _buckets[j] = new Pair(key, val); - _size += 1; - return; - } - // 若遇到指定 key ,则更新对应 val - if (_buckets[j]!.key == key) { - _buckets[j]!.val = val; - return; - } + // 搜索 key 对应的桶索引 + int index = findBucket(key); + // 若找到键值对,则覆盖 val 并返回 + if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) { + _buckets[index]!.val = val; + return; } + // 若键值对不存在,则添加该键值对 + _buckets[index] = new Pair(key, val); + _size++; } /* 删除操作 */ void remove(int key) { - int index = hashFunc(key); - // 线性探测,从 index 开始向后遍历 - for (int i = 0; i < _capacity; i++) { - // 计算桶索引,越过尾部返回头部 - int j = (index + i) % _capacity; - // 若遇到空桶,说明无此 key ,则直接返回 - if (_buckets[j] == null) { - return; - } - // 若遇到指定 key ,则标记删除并返回 - if (_buckets[j]!.key == key) { - _buckets[j] = _removed; - _size -= 1; - return; - } + // 搜索 key 对应的桶索引 + int index = findBucket(key); + // 若找到键值对,则用删除标记覆盖它 + if (_buckets[index] != null && _buckets[index] != _TOMBSTONE) { + _buckets[index] = _TOMBSTONE; + _size--; } } @@ -2489,7 +2492,7 @@ comments: true _size = 0; // 将键值对从原哈希表搬运至新哈希表 for (Pair? pair in bucketsTmp) { - if (pair != null && pair != _removed) { + if (pair != null && pair != _TOMBSTONE) { put(pair.key, pair.val); } } @@ -2498,10 +2501,12 @@ comments: true /* 打印哈希表 */ void printHashMap() { for (Pair? pair in _buckets) { - if (pair != null) { - print("${pair.key} -> ${pair.val}"); + if (pair == null) { + print("null"); + } else if (pair == _TOMBSTONE) { + print("TOMBSTONE"); } else { - print(null); + print("${pair.key} -> ${pair.val}"); } } } diff --git a/chapter_hashing/hash_map.md b/chapter_hashing/hash_map.md index ffd5c87b4..f96faae5c 100755 --- a/chapter_hashing/hash_map.md +++ b/chapter_hashing/hash_map.md @@ -309,12 +309,12 @@ comments: true cout << kv.first << " -> " << kv.second << endl; } // 单独遍历键 key - for (auto key: map) { - cout << key.first << endl; + for (auto kv: map) { + cout << kv.first << endl; } // 单独遍历值 value - for (auto val: map) { - cout << val.second << endl; + for (auto kv: map) { + cout << kv.second << endl; } ``` @@ -1408,7 +1408,126 @@ index = hash(key) % capacity typedef struct pair pair; - [class]{arrayHashMap}-[func]{} + /* 基于数组简易实现的哈希表 */ + struct arrayHashMap { + pair *buckets[HASH_MAP_DEFAULT_SIZE]; + }; + + typedef struct arrayHashMap arrayHashMap; + + /* 哈希表初始化函数 */ + arrayHashMap *newArrayHashMap() { + arrayHashMap *map = malloc(sizeof(arrayHashMap)); + return map; + } + + /* 添加操作 */ + void put(arrayHashMap *d, const int key, const char *val) { + pair *pair = malloc(sizeof(pair)); + pair->key = key; + pair->val = malloc(strlen(val) + 1); + strcpy(pair->val, val); + + int index = hashFunc(key); + d->buckets[index] = pair; + } + + /* 删除操作 */ + void removeItem(arrayHashMap *d, const int key) { + int index = hashFunc(key); + free(d->buckets[index]->val); + free(d->buckets[index]); + d->buckets[index] = NULL; + } + + /* 获取所有键值对 */ + void pairSet(arrayHashMap *d, mapSet *set) { + pair *entries; + int i = 0, index = 0; + int total = 0; + + /* 统计有效键值对数量 */ + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + total++; + } + } + + entries = malloc(sizeof(pair) * total); + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + entries[index].key = d->buckets[i]->key; + entries[index].val = malloc(strlen(d->buckets[i]->val + 1)); + strcpy(entries[index].val, d->buckets[i]->val); + index++; + } + } + + set->set = entries; + set->len = total; + } + + /* 获取所有键 */ + void keySet(arrayHashMap *d, mapSet *set) { + int *keys; + int i = 0, index = 0; + int total = 0; + + /* 统计有效键值对数量 */ + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + total++; + } + } + + keys = malloc(total * sizeof(int)); + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + keys[index] = d->buckets[i]->key; + index++; + } + } + + set->set = keys; + set->len = total; + } + + /* 获取所有值 */ + void valueSet(arrayHashMap *d, mapSet *set) { + char **vals; + int i = 0, index = 0; + int total = 0; + + /* 统计有效键值对数量 */ + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + total++; + } + } + + vals = malloc(total * sizeof(char *)); + for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) { + if (d->buckets[i] != NULL) { + vals[index] = d->buckets[i]->val; + index++; + } + } + + set->set = vals; + set->len = total; + } + + /* 打印哈希表 */ + void print(arrayHashMap *d) { + int i; + mapSet set; + pairSet(d, &set); + pair *entries = (pair *)set.set; + for (i = 0; i < set.len; i++) { + printf("%d -> %s\n", entries[i].key, entries[i].val); + } + free(set.set); + } ``` === "Zig"