二、递归与分治策略(Fibonacci数列时间复杂度与空间复杂度)

1 表达式

F ( n ) = { 1 n = 0 , 1 F ( n − 1 ) + F ( n − 2 ) n > 1 F(n)=\begin{cases} 1& {n=0,1} \\ F(n-1)+F(n-2) & n>1\end{cases}F(n)={1F(n1)+F(n2)n=0,1n>1

2 代码

public static int fib(int n){
	if (n == 0 || n == 1) return 1;
	else{
		return fib(n-1) + fib(n-2);
	}
}

3 复杂度分析

在这里插入图片描述

3.1 空间复杂度

  • 每次调用函数都要一个空间来存储传进来的整数,并且函数运行完成并返回时,空间被释放,因此空间复杂度为树的深度n nn,即O ( n ) O(n)O(n)

3.2 时间复杂度

  • 上图中时间复杂度相当于所有节点的个数,不是完全二叉树,但是还是指数级别的,因此时间复杂度为O ( 2 n ) O(2^n)O(2n)

3.3 问题

  • 非递归时间复杂度和空间复杂度为多少?

  • 代码:

    public static int fib(int n){
    	int front=1;
    	int behind=1;
    	int temp;
    	for(int i = 2;i <= n-1;i++){
    		temp = front + behind;
    		front = behind;
    		behind = temp;
    	}
    	return behind;
    }
    
    • 空间复杂度:由于程序运行中只用了有限个变量,且与问题规模n无关,所以空间复杂度为O ( 1 ) O(1)O(1)
    • 时间复杂度:一层for循环,一共执行了n-2次,所以时间复杂度为O ( n ) O(n)O(n)

版权声明:本文为u012011912原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。