zoukankan      html  css  js  c++  java
  • 009 变态跳台阶

    1.题目

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

    2.思路

      这里主要有两种思路,我感觉第二种更好理解一点。

      1.

      假设:f(n)表示:n个台阶第一次1,2,...n阶的跳法数;

      若第一次跳了1阶,则还剩n-1阶,
      假设:f(n-1)表示:n-1个台阶第一次1,2,...n-1阶的跳法数;
      若第一次跳了2阶,则还剩n-2阶,
      假设:f(n-2)表示:n-1个台阶第一次1,2,...n-2阶的跳法数;
         // ...
      把所以可能的情况(第一次可能跳1,2,...,n阶)加起来:
      可以求出:f(n) = f(n-1) + f(n-2) + ... + f(1)
      递归:f(n-1) = f(n-2) + ... + f(1)
      可以求出:f(n) = 2*f(n-1) 
      2.
      每个台阶可以跳或者不跳
     
    3.程序
     1 package first;
     2 
     3 public class JumpFloorII {
     4     public static void main(String[] args){
     5         //
     6         int a=JumpFloorII(3);
     7         System.out.println(a);
     8         //
     9         int b=JumpFloorII2(3);
    10         System.out.println(b);
    11         //
    12         int c=JumpFloorII3(3);
    13         System.out.println(c);
    14         //
    15         int d=JumpFloorII4(3);
    16         System.out.println(d);
    17     }
    18 
    19     public static  int JumpFloorII(int target) {
    20         if(target<=0)
    21             return 0;
    22         return 1<<(target-1);
    23     }
    24 
    25     public static int JumpFloorII2(int target){
    26         if(target<=0){
    27             return 0;
    28         }else if(target==1){
    29             return 1;
    30         }else
    31             return 2*JumpFloorII2(target-1);
    32     }
    33 
    34     public static int JumpFloorII3(int target){
    35         if (target <= 0) return 0;
    36         return (int) Math.pow(2, target - 1);
    37     }
    38 
    39     public static int JumpFloorII4(int target){
    40         if (target==0)
    41             return 0;
    42         if (target==1)
    43             return 1;
    44         int a=1;   //第一次的方法
    45         int b=2;   //第二次的方法
    46         for(int i=2;i<=target;i++){
    47             b=2*a;  //2*上一次的方法
    48             a=b;    //将值传递,然后继续下一步计算
    49         }
    50         return b;
    51     }
    52 
    53 
    54 }
  • 相关阅读:
    网页包抓取工具Fiddler工具简单设置
    django-Celery分布式队列简单使用
    django-nginx与uwsgi项目部署
    mysql数据库备份之主从同步配置
    mysql开启二进制日志
    python-django框架中使用七牛云
    python-django框架中使用FastDFS分布式文件系统
    python-django框架中使用docker和elasticsearch配合实现搜索功能
    C#_WPF中创建二维码、识别二维码
    读书笔记:《企业IT架构转型之道-阿里巴巴中台战略思想与架构实战》
  • 原文地址:https://www.cnblogs.com/juncaoit/p/10418175.html
Copyright © 2011-2022 走看看