zoukankan      html  css  js  c++  java
  • 递归_青蛙跳台阶(变态版)

    题目描述

    一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

    我的解法

    public int JumpFloor1(int target) {
        if (target == 1) {
            return 1;
        } else {
            int total = 0;
            for (int i = 1; i < target; i++) {
                total += JumpFloorII(target - i);
            }
            return total+1;
        }
    }
    

    大佬的解法

    ① f(n) = f(n-1) + f(n-2) +f(n-3) + ... + f(2) + f(1)

    ② f(n-1) = f(n-2) +f(n-3) + ... + f(2) + f(1)

    由①②得,f(n) = 2f(n-1);

    public static int jumpFloor2(int target) {
        if (target == 1) {
            return 1;
        } else {
            return 2 * jumpFloor2(target - 1);
        }
    }
    

    终极解法

    f(n) = 2f(n-1) (n>=2)
    f(n) = 1 (n=1)

    递归方程求解:

    f( n ) = 2f( n - 1 )

    ​ = 2*2f( (n-1) - 1 ) = 22f( n - 2 )

    ​ = 2*2*2f( (n-2) - 1 ) = 23f( n - 3 )

    ​ =2*2*2*2......*2f( (n-(n-3)) -1) = 2n-2f( n - (n-2) ) = 2n-2f( 2 )

    ​ =2*2*2*2......*2f( (n-(n-2)) -1) = 2n-1f( n - (n-1) ) = 2n-1f( 1 ) = 2n-1

    public int JumpFloor3(int target) {
        return (int) Math.pow(2, target - 1);
    }
    
  • 相关阅读:
    Linux 命令
    Linux 命令
    Linux 命令
    Linux 命令
    121.Best Time to Buy and Sell Stock---dp
    136.Single Number---异或、位运算
    141.Linked List Cycle---双指针
    Restful接口设计
    socket网络编程
    107.Binary Tree Level Order Traversal II
  • 原文地址:https://www.cnblogs.com/XiaoZhengYu/p/12594412.html
Copyright © 2011-2022 走看看