Fibonacci

本文探讨了斐波那契数列的计算方法,包括迭代和普通递归两种方式。迭代方法通过循环逐步计算每个数,而递归方法则直接通过函数调用来实现,但后者在大量计算时可能遇到性能问题。

Description

Find the Nth number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

  • The first two numbers are 0 and 1.
  • The i th number is the sum of i-1 th number and i-2 th number.

The first ten numbers in Fibonacci sequence is:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

Example

Given 1, return 0

Given 2, return 1

Given 10, return 34


    此题有三种解法:迭代、普通递归

    (1)迭代

    每一次对过程的重复称为一次“迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。

int Fibonacci_1(int n) {
	
	int pre = 0, cur = 1;
	for (int i = 1; i < n; i++) {
		cur += pre;
		pre = cur - pre;
	}
	return pre;
}

    注意返回值是pre。

   (2)普通递归

int Fibonacci_2(int n) {

	if (n == 1) return 0;
	else if (n == 2) return 1;
	else return Fibonacci_2(n - 1) + Fibonacci_2(n - 2);
}

    代码看似简洁易于理解对吧?其实这种解法会超时。为什么?内存会为递归函数的每次调用在栈中分配一块存储空间保存函数调用信息,且递归函数调用的返回值依赖于下一次函数调用的返回值。在函数调用结束之前,所占用的堆栈资源是无法释放的,所以递归过程中会保存许多中间函数的堆栈,十分占用内存空间,经常会出现超时或者程序崩溃等异常情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值