码迷,mamicode.com
首页 > 其他好文 > 详细

斐波那契数列问题及应用

时间:2018-08-14 11:40:18      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:code   青蛙跳   rect   class   i++   覆盖   问题   bsp   stat   

第一题:

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

代码如下:

 1 public class offer7 {
 2     public static int Fibonacci(int n) {
 3         int num1 = 0;
 4         int num2 = 1;
 5         int p = 0; 
 6         if(n==0){
 7             return num1;
 8         }
 9         if(n==1){
10             return num2;
11         }
12         for(int i=0;i<n-1;i++){
13             p = num1 + num2;
14             num1 = num2;
15             num2 = p;
16         }
17         return p;
18     }
19     public static void main(String[] args){
20         int m = Fibonacci(8);
21         System.out.println(m);
22     }
23 }
24 //0 1 1 2 3 5 8 13 21 34

第二题:

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

/*
* 找规律
* 一阶台阶:1
* 2:2
* 3:3
* 4:5
* 5:8
* 6:13
* 就是菲波那切数列
*/

代码如下:

 1 public class offer8 {
 2     public int JumpFloor(int target) {
 3         int num1 = 0;
 4         int num2 = 1;
 5         int p = 0; 
 6         if(target==0){
 7             return 0;
 8         }
 9         if(target==1){
10             return num2;
11         }
12         for(int i=0;i<target;i++){
13             p = num1 + num2;
14             num1 = num2;
15             num2 = p;
16         }
17         return p;
18     }
19 }

第三题:

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

还是找规律,规律如下

0阶台阶:0

1阶台阶:1

2阶台阶:2

3阶台阶:4

4阶台阶:8

。。。

n阶台阶:Math.pow(2,n-1)

代码如下:

1 public class offer9 {
2     public int JumpFloorII(int target) {
3         if(target<=0){
4             return 0;
5         }
6         return (int) Math.pow(2,target-1);
7     }
8 }

第四题:

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

依旧找规律,仍然是转化为斐波那契数列问题

代码如下:

 1 public class Solution {
 2     public int RectCover(int target) {
 3         int num1 = 0;
 4         int num2 = 1;
 5         int p = 0;
 6         if(target==0){
 7             return 0;
 8         }
 9         for(int i=0;i<target;i++){
10             p = num1 + num2;
11             num1 = num2;
12             num2 = p;
13         }
14         return p;
15     }
16 }

 

斐波那契数列问题及应用

标签:code   青蛙跳   rect   class   i++   覆盖   问题   bsp   stat   

原文地址:https://www.cnblogs.com/fanghuiplus/p/9472601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!