【剑指offer】面试题10 - 斐波那契数列及变种问题

面试题10 - 1:斐波那契数列

题目描述:

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。

链接:LeetCode 牛客网

解法一:递归

思路:

image-20210303111025968

class Solution {
    
    
public:
    int Fibonacci(int n) {
    
    
        if(n == 0) return 0;
        if(n == 1) return 1;
        return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
};

解法二:迭代

思路:

  • 迭代 就是把递归的算法用循环实现
class Solution {
    
    
public:
    int Fibonacci(int n) {
    
    
        if(n == 0) return 0;
        if(n == 1) return 1;
        int first = 0;
        int second = 1;
        int ans = 0;
        while(n >= 2)
        {
    
    
            ans = first + second;
            first = second;
            second = ans;
            n--;
        }
        return ans;
    }
};

解法三:开辅助数组存中间值

思路:

  • 将需要计算的 n 的前 n - 1 个中间值计算出来,保存在一个数组中,需要哪个数直接取出哪个数
class Solution {
    
    
public:
    int Fibonacci(int n) {
    
    
        int a[40];
        a[0] = 0;
        a[1] = 1;
        for(int i = 2; i < 40; i++)
            a[i] = a[i-1] + a[i-2];
        return a[n];
    }
};

面试题10 - 2:青蛙跳台

题目描述:

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

链接:LeetCode 牛客网

解法一:斐波那契解法

思路:

  • 解法同斐波那契数列,只是初始值改变
class Solution {
    
    
public:
    int jumpFloor(int n) {
    
    
        if(n == 1) return 1;
        if(n == 2) return 2;
        int first = 1;
        int second = 2;
        int ans = 0;
        while(n > 2)
        {
    
    
            ans = first + second;
            first = second;
            second = ans;
            n--;
        }
        return ans;
    }
};
   first = second;
            second = ans;
            n--;
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45437022/article/details/114306448