今晚八點,接受了某大廠的後臺開發工程師的崗位電話面試。
第一面而已,時常40多分鐘,過程有順暢的部分,也有很坎坷的部分。
現在過了幾個小時,感覺自己真的很差勁啊,還是要勤學苦練。
一番反思之後,補個漏洞吧。也算是自己不白白被這一面。
- 斐波那契數列
問題:一個樓梯有n階,一次走1步或者2步,請問到頂有多少種走法。
分析:
臺階數 | 行走方式 & 行走次數 |
---|---|
1 | 1 1 |
2 | 1+1 / 2 2 |
3 | 1+1+1/1+2/2+1 3 |
4 | 1+1+1+1 /1+1+2/1+2+1/2+1+1/2+2 5 |
n | … f(n-1)+f(n-2) |
一一窮舉出來我們發現,當n個臺階時,它的行走次數是前兩個行走方式次數的和,
即
f(n) = f(n-1) +f(n-2)
接下來寫代碼。
1.遞歸的方式:
#include<iostream>
using namespace std;
int fib(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
else //當n>=2時,就可以套用f(n) = f(n-1)+f(n-2)這個公式了。
return fib(n-1) + fib(n-2);
}
當然,還有非遞歸的解法。
#include<iostream>
using namespace std;
int fib(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
int n1 = 0;
int n2 = 1;
int result = 0;
while(n--)
{
result = n1 + n2;
n1 = n2;
n2 = result;
}
return result;
}