2019-08-24 11:26阅读: 141评论: 0推荐: 0

剑指offer(10)—— 斐波那契数列以及跳台阶问题

总结

2^(n-1)可以用位移操作进行: 1<< (n-1)
如果递归不好思考的话,可以找规律,代码很简单

斐波那契数列(10)

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

n<=39

public class Solution {
    public int Fibonacci(int n) {
        // 先判断n必须在范围内取值
        if(n > 39 && n <= 0) return 0;
        // 为1直接返回
        if(n == 1) return 1;
        
        int a = 0;
        int b = 1;
        int result = 0;
        for(int i = 2;i<=n;i++){
            result = a + b;
            a = b;
            b = result;
        }    
        return result;       
    }
}

跳台阶(10)

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

public class Solution {
    public int JumpFloor(int target) {
        if(target == 1) return 1;
        if(target == 2) return 2;
        int a = 1;
        int b = 2;
        int result = 0;
        for(int i = 3;i<=target;i++){
            result = a + b;
            a = b;
            b = result;
        }
        return result;
    }
}

变态跳台阶

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

class Solution {
    public int JumpFloorII(int target) {
        if(target == 1) return 1;
        return (int)Math.pow(2,target-1);
    }
}

public class Solution {
    public int JumpFloorII(int target) {
        if(target == 1) return 1;
       // return (int)Math.pow(2,target-1);
        return 1<<(target -1);
    }
}

本文作者:benjieqiang

本文链接:https://www.cnblogs.com/benjieqiang/p/11404019.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   benjieqiang  阅读(141)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑
  1. 1 蒹葭(古筝版) 徐潮城
蒹葭(古筝版) - 徐潮城
00:00 / 00:00
An audio error has occurred.

作词 : 诗经

作曲 : 徐潮城

蒹葭-徐潮城

编:刘文

蒹葭苍苍白露为霜

所谓伊人在水一方

溯洄从之道阻且长

溯游水中央

蒹葭萋萋白露未晞

伊人在水湄

溯洄从之道阻且跻

溯游水中坻

蒹葭苍苍白露为霜

所谓伊人在水涘

伊人在水一方

蒹葭采采白露未已

溯洄从之道阻且右

溯游水中沚

蒹葭萋萋白露未晞

伊人在水湄

溯洄从之道阻且跻

溯游水中坻

蒹葭苍苍白露为霜

所谓伊人在水涘

伊人在水一方

蒹葭采采白露未已

溯洄从之道阻且右

溯游水中沚

蒹葭苍苍白露为霜

所谓伊人在水涘

伊人在水一方

蒹葭采采白露未已

溯洄从之道阻且右

溯游水中沚