剑指offer--跳台阶

来源:互联网 发布:网络市场中间商的类型 编辑:程序博客网 时间:2024/05/24 05:32

题目描述

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


分类:数组

解法1:本质也是斐波那契数列
[java] view plain copy
  1. package test;  
  2.   
  3. public class Test3 {              
  4.       
  5.     public int JumpFloor(int target) {  
  6.         if(target==1){  
  7.             return 1;  
  8.         }  
  9.         int arr[] = new int[2];  
  10.         arr[0] = 1;  
  11.         arr[1] = 2;  
  12.         int temp = 0;  
  13.         for(int i=3;i<=target;i++){  
  14.             temp = arr[1];  
  15.             arr[1] = arr[0] + arr[1];  
  16.             arr[0] = temp;  
  17.         }  
  18.         return arr[1];  
  19.     }  
  20.           
  21.     public static void main(String[] args) {  
  22.         Test3 t = new Test3();  
  23.         System.out.println(t.JumpFloor(30));  
  24.     }  
  25. }  

也可以使用递归:
[java] view plain copy
  1. public class Solution {  
  2.     public int JumpFloor(int target) {  
  3.         if(target==1return 1;  
  4.         if(target==2return 2;  
  5.         return JumpFloor(target-1)+JumpFloor(target-2);  
  6.     }  
  7. }  


原文链接  http://blog.csdn.net/crazy__chen/article/details/44985023

原创粉丝点击