zoukankan      html  css  js  c++  java
  • [leetCode]剑指 Offer 10- I、II. 斐波那契数列(青蛙跳台阶)

    在这里插入图片描述

    递归

    这道题很容易用递归求解,但是由于递归存在很多重复计算因此这种解法不实用,会超时。

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

    动态规化

    可以使用数组记录下记录下每个结果这样就避免了重复计算

    class Solution {
        public int fib(int n) {
           if(n == 0) return 0;
           if(n == 1) return 1;
           int[] result = new int[n + 1];
           result[0] = 0;
           result[1] = 1;
           for(int i = 2; i <= n; i++){
               result[i] =  (int)((result[i-1] + result[i-2])%(1e9+7)); 
           }
           return result[n];
        }
    }
    

    由于求f(N)只跟之前两个状态有关,所以可以使用两个变量来保存之前两个状态

    class Solution {
        public int fib(int n) {
           if(n == 0) return 0;
           if(n == 1) return 1;
           int fibOne = 1;
           int fibTwo = 0;
           int fibN = 0;
           for(int i = 2; i <= n; i++){
              fibN =  (int)((fibOne + fibTwo)%(1e9+7));
              fibTwo = fibOne;
              fibOne = fibN;
           }
           return fibN;
        }
    }
    

    在这里插入图片描述

    解法

    这道题其实就是斐波那契数列,如果只跳一级台阶则有1种跳法,如果跳两级台阶则有两种跳法({1,1},{2}). 设跳n级台阶的方法数为 f ( n ) f(n) f(n),那么跳n级台阶,第一次跳有两种选择:

    1. 跳一级,跳法数为剩下跳台阶的跳法,有 f ( n − 1 ) f(n-1) f(n1)
    2. 跳两级,跳法数为剩下跳台阶的跳法,有 f ( n − 2 ) f(n-2) f(n2)

    所以一共有 f ( n ) = f ( n − 1 ) + f ( n − 2 ) f(n) = f(n-1) +f(n-2) f(n)=f(n1)+f(n2)

    class Solution {
        public int numWays(int n) {
            if(n == 1) return 1;
            if(n == 2) return 2;
            int jumpN = 1;
            int jump1 = 2;//跳2级台阶有2种跳法
            int jump2 = 1;//跳一级台阶有1种跳法
            for(int i = 3; i <= n; i++){
                jumpN = (int)((jump1 +jump2)%(1e9+7));
                jump2 = jump1;
                jump1 = jumpN;
            }
            return jumpN;
        }
    }
    

    [LeetCode]70.爬楼梯这题相同

  • 相关阅读:
    LeetCode-160. Intersection of Two Linked Lists
    LeetCode-328. Odd Even Linked List
    LeetCode-234. Palindrome Linked List
    Trie树
    圆圈中最后剩下的数字
    LeetCode-215. Kth Largest Element in an Array
    n个骰子的和
    DFS & BFS
    ubuntu14.04安装显卡驱动(转载)
    Ubuntu 14.04 配置caffe环境
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859982.html
Copyright © 2011-2022 走看看