剑指Offer——(7)斐波那契数列
来源:互联网 发布:mysql exists 原理 编辑:程序博客网 时间:2024/06/07 03:58
题目说明:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
实现如下:
//0 1 1 2 3 5 8 13 21...//简洁的递归,但是注意消除重复计算项,采用map存储已计算的n的valueclass Solution {public: map<int, long long> m; long long num; int Fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; else { map<int, long long>::iterator it = m.find(n);//查找是否已计算过 if (m.end() == it)//之前没算过,进行计算,再insert { num = Fibonacci(n - 1) + Fibonacci(n - 2); m.insert(pair<int, long long>(n, num)); return num; } else return it->second;//若之前算过,直接get second } }};//O(n)的循环方法,没有什么好解释的...→_→class Solution {public: int Fibonacci(int n) { long long res[2] = { 0,1 }; long long tmp = 0; if (n == 0) return 0; else if (n == 1) return 1; else { for (int i = 2; i <= n; ++i) { //空瓶子swap tmp = res[0] + res[1]; res[0] = res[1]; res[1] = tmp; } return res[1]; } }};
0 1
- 《剑指offer》—7、斐波那契数列
- 剑指offer(7)—斐波那契数列
- 《剑指offer》——斐波那契数列
- 剑指offer——斐波那契数列
- 斐波那契数列——剑指offer
- 剑指offer——斐波那契数列
- 剑指offer——斐波那契数列
- 剑指offer——7.斐波那契数列
- 剑指offer——斐波那契数列
- 剑指offer——斐波那契数列
- 剑指offer(7)-斐波那契数列
- 剑指offer--(7) 斐波那契数列
- 剑指offer—斐波那契数列
- 剑指offer刷题—斐波那契数列
- 剑指Offer——(7)斐波那契数列
- 【剑指offer】斐波那契数列
- 剑指offer--斐波那契数列
- 剑指Offer-斐波那契数列
- 简单拍照
- python 爬虫之路教程
- myeclipse加载tomcat包
- 线程池的原理和连接池的原理
- 有关iOS命名规范
- 剑指Offer——(7)斐波那契数列
- springboot使用Freemarker继承
- android View coordinate(坐标)
- Android 状态栏背景设置
- qt之 调用摄像头
- 项目中如何使用solr
- app widget简单用法(2)
- Ubuntu14.04 apache2 配置 CGI(并测试:shell,可执行文件,python)
- Node.js-入门三--文件I/O