递归是一种编程技巧,它允许一个函数调用自身来解决问题。递归通常用于解决可以分解为更小相似问题的问题。Fibonacci序列是一个经典的递归问题,其中每个数字是前两个数字的和。
以下是在Swift Playground中使用递归打印Fibonacci序列的示例代码:
func fibonacci(_ n: Int) -> Int {
if n <= 1 {
return n
} else {
return fibonacci(n - 1) + fibonacci(n - 2)
}
}
func printFibonacciSequence(_ count: Int) {
for i in 0..<count {
print(fibonacci(i), terminator: " ")
}
print()
}
// 打印前10个Fibonacci数字
printFibonacciSequence(10)
原因:每次函数调用都会在栈上分配内存,递归调用过多会导致栈空间耗尽。
解决方法:
func fibonacciIterative(_ n: Int) -> Int {
if n <= 1 {
return n
}
var a = 0
var b = 1
for _ in 2...n {
let temp = a + b
a = b
b = temp
}
return b
}
func printFibonacciSequenceIterative(_ count: Int) {
for i in 0..<count {
print(fibonacciIterative(i), terminator: " ")
}
print()
}
// 打印前10个Fibonacci数字
printFibonacciSequenceIterative(10)
通过以上方法,你可以在Swift Playground中使用递归或迭代的方式打印Fibonacci序列,并解决递归调用过多导致的栈溢出问题。
领取专属 10元无门槛券
手把手带您无忧上云