What is a non recursive solution for Fibonacci-like sequence in Java?

前端 未结 10 1568
Happy的楠姐
Happy的楠姐 2020-12-01 18:23

Given this pseudo code of a function

f(0) = 1; 
f(1) = 3; 
f(n) = 3 * f(n - 1) - f(n - 2); // for n >= 2.

Is there a non recursive way o

10条回答
  •  天涯浪人
    2020-12-01 19:07

    Here is simply a function with minimum line of code and maximum flexibility.

    You can add any "initial values" and any other recursive "function" you want simply.

    def fib(n):
      fibs = [1, 3]       # <--  your initial values here 
      if n == 1:
        return fibs[0]
      if n == 2:
        return fibs[:1]
      for i in range(2, n):
        fibs.append(3*fibs[-1] - fibs[-2])  # <-- your function here
      return fibs
    

    And the result is:

    n=10
    print(fib(n))
    
    [1, 3, 8, 21, 55, 144, 377, 987, 2584, 6765]
    

提交回复
热议问题