牛客网剑指offer递归和迭代题目总结(共3道)

牛客网剑指offer递归和迭代题目总结(共3道)

1、斐波那契数列(剑指7)

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

class Solution {
public:
    int Fibonacci(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        int first=0,second=1,ans=0;
        for(int i=2;i<=n;i++){
            ans=first+second;
            first=second;
            second=ans;
        }
        return ans;
    }
};

2、跳台阶(剑指8,同leetcode70)

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

同上

class Solution {
public:
    int jumpFloor(int number) {
        if(number==1) return 1;
        if(number==2) return 2;
        int first=1,second=2,ans;
        for(int i=3;i<=number;i++){
            ans=first+second;
            first=second;
            second=ans;
        }
        return ans;
    }
};

3、矩阵覆盖(剑指10)

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

比如n=3时,2*3的矩形块有3种覆盖方法:

class Solution {
public:
    int rectCover(int number) {
        if(number==1) return 1;
        if(number==2) return 2;
        int first=1,second=2,ans=0;
        for(int i=3;i<=number;i++){
            ans=first+second;
            first=second;
            second=ans;
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/yjcoding/p/13217050.html