更新代码块
This commit is contained in:
@@ -18,7 +18,7 @@
|
||||
|
||||
先来看一下求斐波那契数的递归写法。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
int fibonacci(int i) {
|
||||
if(i <= 0) return 0;
|
||||
if(i == 1) return 1;
|
||||
@@ -50,7 +50,7 @@ int fibonacci(int i) {
|
||||
|
||||
以下为C++代码,来测一下,让我们输入n的时候,这段递归求斐波那契代码的耗时。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
@@ -99,7 +99,7 @@ int main()
|
||||
|
||||
其实罪魁祸首就是这里的两次递归,导致了时间复杂度以指数上升。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
return fibonacci(i-1) + fibonacci(i-2);
|
||||
```
|
||||
|
||||
@@ -107,7 +107,7 @@ return fibonacci(i-1) + fibonacci(i-2);
|
||||
|
||||
来看一下如下代码:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
// 版本二
|
||||
int fibonacci(int first, int second, int n) {
|
||||
if (n <= 0) {
|
||||
@@ -138,7 +138,7 @@ int fibonacci(int first, int second, int n) {
|
||||
|
||||
此时再来测一下耗时情况验证一下:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
@@ -208,7 +208,7 @@ int main()
|
||||
|
||||
那么每次递归的空间复杂度是O(1), 调用栈深度为n,所以这段递归代码的空间复杂度就是O(n)。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
int fibonacci(int i) {
|
||||
if(i <= 0) return 0;
|
||||
if(i == 1) return 1;
|
||||
@@ -227,7 +227,7 @@ int fibonacci(int i) {
|
||||
|
||||
带大家再分析一段二分查找的递归实现。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
int binary_search( int arr[], int l, int r, int x) {
|
||||
if (r >= l) {
|
||||
int mid = l + (r - l) / 2;
|
||||
|
||||
Reference in New Issue
Block a user