|
|
|
@ -4,6 +4,8 @@
|
|
|
|
|
|
|
|
|
|
package chapter_computational_complexity
|
|
|
|
|
|
|
|
|
|
import "container/list"
|
|
|
|
|
|
|
|
|
|
/* 递归 */
|
|
|
|
|
func recur(n int) int {
|
|
|
|
|
// 终止条件
|
|
|
|
@ -16,6 +18,26 @@ func recur(n int) int {
|
|
|
|
|
return n + res
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 使用迭代模拟递归 */
|
|
|
|
|
func forLoopRecur(n int) int {
|
|
|
|
|
// 使用一个显式的栈来模拟系统调用栈
|
|
|
|
|
stack := list.New()
|
|
|
|
|
res := 0
|
|
|
|
|
// 递:递归调用
|
|
|
|
|
for i := n; i > 0; i-- {
|
|
|
|
|
// 通过“入栈操作”模拟“递”
|
|
|
|
|
stack.PushBack(i)
|
|
|
|
|
}
|
|
|
|
|
// 归:返回结果
|
|
|
|
|
for stack.Len() != 0 {
|
|
|
|
|
// 通过“出栈操作”模拟“归”
|
|
|
|
|
res += stack.Back().Value.(int)
|
|
|
|
|
stack.Remove(stack.Back())
|
|
|
|
|
}
|
|
|
|
|
// res = 1+2+3+...+n
|
|
|
|
|
return res
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 尾递归 */
|
|
|
|
|
func tailRecur(n int, res int) int {
|
|
|
|
|
// 终止条件
|
|
|
|
|