Sword finger offer question 9: Fibonacci series

Keywords: Java Python

Title Description

Topic 1: we all know Fibonacci series. Now you need to input an integer n. please output the nth item of Fibonacci series. N<=39

Topic 2: a frog can jump up one or two steps at a time. Find out how many ways the frog can jump to an n-level step.

Experimental platform: Niu Ke LAN

Topic 1

On niuke.com, this problem is only allowed to be solved circularly. If recursion is used, stack overflow ror exception will be reported, that is, stack overflow. We can know that the efficiency of recursion is very low, and the time complexity is exponentially increasing.

java:

public class Solution {
    public int Fibonacci(int n) {
        int fibonacci1 = 0;
        int fibonacci2 = 1;
        int fibonacci = 0;
        if (n == 0) {
            return fibonacci1;
        }else if (n==1) {
            return fibonacci2;
        } else {
            for (int i = 2; i <= n; i++) {
                fibonacci = fibonacci1 + fibonacci2;
                fibonacci1 = fibonacci2;
                fibonacci2 = fibonacci;
            }
            return fibonacci;
        }
    }
}

python:

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        fibonacci1 = 0
        fibonacci2 = 1
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            for i in range(2, n+1):
                fibonacci = fibonacci1 + fibonacci2
                fibonacci1 = fibonacci2
                fibonacci2 = fibonacci
            return fibonacci

Topic two

Solutions


java:

public class Solution {
    public int JumpFloor(int target) {
        int sum1 = 1;
        int sum2 = 2;
        int sum = 0;
        if (target == 1) {
            return sum1;
        } else if (target == 2) {
            return sum2;
        } else {
            for (int i = 2; i < target; i++) {
                sum = sum1 + sum2;
                sum1 = sum2;
                sum2 = sum;
            }
            return sum;
        }
    }
}

python:

Just make some changes as before

Posted by dfego on Sat, 04 Apr 2020 08:57:38 -0700