[DP]509. Fibonacci Number
2021/7/17 6:05:21
本文主要是介绍[DP]509. Fibonacci Number,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
509. Fibonacci Number
Difficulty: 简单
The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n
, calculate F(n)
.
Example 1:
Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Constraints:
0 <= n <= 30
Solution 1
Language: c++
class Solution { public: int fib(int n) { if(n == 0 || n == 1) return n; else return fib(n-1)+fib(n-2); } };
Language: python
class Solution: def fib(self, n: int) -> int: if n == 1 or n == 0: return n else: return self.fib(n-1) + self.fib(n-2)
使用递归的,重复计算了很多次,不过考虑到不超过30次,其实还能接受,但是如果能记录下重复计算的结果,使用空间换时间的思路。
Solution 2
Language: c++
class Solution { public: int fib(int n) { if (n == 0 || n == 1) return n; int a = 0,b = 1; for(int i = 2;i<=n;++i){ b = a + b; a = b - a; } return b; } };
Language: python
class Solution: def fib(self, n: int) -> int: if n == 1 or n == 0: return n a,b=0,1 for i in range(1,n): b = a + b a = b - a return b
去除掉重复的计算,速度也会快不少,使用的空间也只有O(1)。
最后贴出出lc的运行消耗对比
这篇关于[DP]509. Fibonacci Number的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-22怎么通过控制台去看我的页面渲染的内容在哪个文件中呢-icode9专业技术文章分享
- 2024-12-22el-tabs 组件只被引用了一次,但有时会渲染两次是什么原因?-icode9专业技术文章分享
- 2024-12-22wordpress有哪些好的安全插件?-icode9专业技术文章分享
- 2024-12-22wordpress如何查看系统有哪些cron任务?-icode9专业技术文章分享
- 2024-12-21Svg Sprite Icon教程:轻松入门与应用指南
- 2024-12-20Excel数据导出实战:新手必学的简单教程
- 2024-12-20RBAC的权限实战:新手入门教程
- 2024-12-20Svg Sprite Icon实战:从入门到上手的全面指南
- 2024-12-20LCD1602显示模块详解
- 2024-12-20利用Gemini构建处理各种PDF文档的Document AI管道