[英]Recursive Fibonacci function in swift
I tried to write recursive function for Fibonacci sequence.我尝试为斐波那契数列编写递归 function。 I used an array to save precalculated elements to improve algorithm(which is a common way to do).
我使用数组来保存预先计算的元素以改进算法(这是一种常见的做法)。
Here is my code:这是我的代码:
var n = Int(readLine()!)
var arr = [Int](repeating:0, count:n!)
arr[0] = 1
arr[1] = 1
arr[2] = 2
func fib(n : Int, arr: inout [Int]) -> (Int,[Int]){
if arr[0] != 0 {
return (arr[n],arr)
}
arr[n] = fib(n: n - 1,arr: &arr).0 + fib(n: n - 2,arr: &arr).0
return (arr[n],arr)
}
n! -= 1
print(fib(n:n! ,arr: &arr).0)
Notice: 3 < n注意:3 < n
The answer for any integer as n is 0.对于 n 为 0 的任何 integer 的答案。
How can I fix it?我该如何解决?
I know that using global variables are much easier(for saving operation), but i don't know how to do that.我知道使用全局变量要容易得多(用于保存操作),但我不知道该怎么做。
The mistake seems to be in the first if statement:错误似乎出现在第一个 if 语句中:
if arr[0] != 0 {
return (arr[n], arr)
}
If the first element of the array is not 0, then you return arr[n]
.如果数组的第一个元素不为 0,则返回
arr[n]
。 Well, arr[0]
is always 1, so the condition is always true, but arr[n]
is initially 0 for all n >= 3, which is what caused the observed behaviour.好吧,
arr[0]
始终为 1,因此条件始终为真,但对于所有 n >= 3, arr[n]
最初为 0,这就是导致观察到的行为的原因。
I think you meant to say:我想你的意思是:
if arr[n] != 0 {
Also, the function doesn't need to return the array since you are using inout
- passing the array by reference.此外, function 不需要返回数组,因为您正在使用
inout
- 通过引用传递数组。 You are not using the second item of the tuple anywhere, are you?您没有在任何地方使用元组的第二项,是吗? So the function can be written as:
所以 function 可以写成:
func fib(n : Int, arr: inout [Int]) -> Int {
if arr[n] != 0 {
return arr[n]
}
arr[n] = fib(n: n - 1,arr: &arr) + fib(n: n - 2,arr: &arr)
return arr[n]
}
func fibonacciOf(_ number: Int) -> Int {
if number == 1 || number == 2 {
return 1
}
return fibonacciOf(number - 2) + fibonacciOf(number - 1)
}
print(fibonacciOf(5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.