mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-05 13:15:30 +08:00
Add comparison between iteration and recursion.
Fix the figure of tail recursion. Fix two links.
This commit is contained in:
@ -16,6 +16,23 @@ def recur(n: int) -> int:
|
||||
return n + res
|
||||
|
||||
|
||||
def for_loop_recur(n: int) -> int:
|
||||
"""使用迭代模拟递归"""
|
||||
# 使用一个显式的栈来模拟系统调用栈
|
||||
stack = []
|
||||
res = 0
|
||||
# 递:递归调用
|
||||
for i in range(n, 0, -1):
|
||||
# 通过“入栈操作”模拟“递”
|
||||
stack.append(i)
|
||||
# 归:返回结果
|
||||
while stack:
|
||||
# 通过“出栈操作”模拟“归”
|
||||
res += stack.pop()
|
||||
# res = 1+2+3+...+n
|
||||
return res
|
||||
|
||||
|
||||
def tail_recur(n, res):
|
||||
"""尾递归"""
|
||||
# 终止条件
|
||||
@ -42,6 +59,9 @@ if __name__ == "__main__":
|
||||
res = recur(n)
|
||||
print(f"\n递归函数的求和结果 res = {res}")
|
||||
|
||||
res = for_loop_recur(n)
|
||||
print(f"\n使用迭代模拟递归求和结果 res = {res}")
|
||||
|
||||
res = tail_recur(n, 0)
|
||||
print(f"\n尾递归函数的求和结果 res = {res}")
|
||||
|
||||
|
Reference in New Issue
Block a user