版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ns708865818/article/details/88076627
比较经典的算法题,Fibonacci序列:
solution 1 :递归
class Solution {
public:
int fib(int N) {
if(N<=1){
return N;
}
return fib(N-1) + fib(N-2);
}
};
solution2:DP
class Solution {
public:
int fib(int N) {
if(N<=1){
return N;
}
int ret[N+1];
ret[0] = 0;
ret[1] = 1;
for(int i = 2;i<=N;i++){
ret[i] = ret[i-1] + ret[i-2];
}
return ret[N];
}
};
solution3:iterative method
class Solution {
public:
int fib(int N) {
if(N<2){
return N;
}
int a = 0;
int b = 1;
int c = 0;
for(int i = 2;i<=N;i++){
c = a + b;
a = b;
b = c;
}
return c;
}
};