Skip to content

Commit c41dc39

Browse files
committed
Add solution for exercise 3-27
1 parent 863b4a4 commit c41dc39

File tree

3 files changed

+75
-1
lines changed

3 files changed

+75
-1
lines changed

README.org

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
习题完成情况:
2626
- 章节一: 43/46
2727
- 章节二: 88/97
28-
- 章节三: 26/82
28+
- 章节三: 27/82
2929
- 章节四: TODO
3030
- 章节五: TODO
3131
* 运行

chapter3/exercise3-27.org

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#+LATEX_CLASS: ramsay-org-article
2+
#+LATEX_CLASS_OPTIONS: [oneside,A4paper,12pt]
3+
#+AUTHOR: Ramsay Leung
4+
5+
#+DATE: 2025-07-01 Tue 22:53
6+
7+
使用 Plantuml 的 activity 图会更直观:
8+
9+
#+begin_src plantuml :file ../img/exercise3-27-memory-fib.png :exports results
10+
@startuml
11+
title 记忆化斐波那契计算 (memo-fib 3)
12+
13+
start
14+
15+
:初始化环境;
16+
note right
17+
memo-fib = (memoize fib)
18+
环境E1 = { f: 原始fib函数, table: {} }
19+
end note
20+
21+
partition "计算 (memo-fib 3)" {
22+
:检查table中是否有key=3;
23+
if (存在?) then (否)
24+
:调用(f 3)即原始fib函数;
25+
26+
partition "计算 (memo-fib 2)" {
27+
:检查table中key=2;
28+
if (存在?) then (否)
29+
:调用(f 2);
30+
31+
partition "计算 (memo-fib 1)" {
32+
:检查table中key=1;
33+
if (存在?) then (否)
34+
:返回1;
35+
:存入table[1]=1;
36+
endif
37+
}
38+
39+
partition "计算 (memo-fib 0)" {
40+
:检查table中key=0;
41+
if (存在?) then (否)
42+
:返回0;
43+
:存入table[0]=0;
44+
endif
45+
}
46+
47+
:计算1+0=1;
48+
:存入table[2]=1;
49+
endif
50+
}
51+
52+
partition "计算 (memo-fib 1)" {
53+
:直接从table获取1;
54+
}
55+
56+
:计算1+1=2;
57+
:存入table[3]=2;
58+
endif
59+
}
60+
61+
:返回结果2;
62+
stop
63+
64+
@enduml
65+
#+end_src
66+
67+
#+RESULTS:
68+
[[file:../img/exercise3-27-memory-fib.png]]
69+
70+
#+begin_quote
71+
如果简单地将 memo-fib 定义为 (memoize fib) 这一模式还能工作吗?
72+
#+end_quote
73+
74+
不能,因为 =fib= 递归调用的是 =fib= 而非 =memo-fib=,意味计算结果不会被保存到 =table= 中,时间复杂度还是指数级。

img/exercise3-27-memory-fib.png

75 KB
Loading

0 commit comments

Comments
 (0)