Files
hello-algo/en/codes/go/chapter_computational_complexity/recursion.go
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

62 lines
1.2 KiB
Go

// File: recursion.go
// Created Time: 2023-08-28
// Author: Reanon (793584285@qq.com)
package chapter_computational_complexity
import "container/list"
/* Recursion */
func recur(n int) int {
// Base case
if n == 1 {
return 1
}
// Recurse: make a recursive call
res := recur(n - 1)
// Unwind: return the result
return n + res
}
/* Simulate recursion using iteration */
func forLoopRecur(n int) int {
// Use an explicit stack to simulate the system call stack
stack := list.New()
res := 0
// Descending: simulate recursive calls
for i := n; i > 0; i-- {
// Simulate recursive calls by pushing onto the stack
stack.PushBack(i)
}
// Unwinding: simulate returning results
for stack.Len() != 0 {
// Simulate unwinding by popping from the stack
res += stack.Back().Value.(int)
stack.Remove(stack.Back())
}
// res = 1+2+3+...+n
return res
}
/* Tail recursion */
func tailRecur(n int, res int) int {
// Base case
if n == 0 {
return res
}
// Tail-recursive call
return tailRecur(n-1, res+n)
}
/* Fibonacci sequence: recursion */
func fib(n int) int {
// Base cases: f(1) = 0, f(2) = 1
if n == 1 || n == 2 {
return n - 1
}
// Recursive calls: f(n) = f(n-1) + f(n-2)
res := fib(n-1) + fib(n-2)
// Return the result f(n)
return res
}