LeetCode 509. 斐波那契数
题目描述
解题思路
一、迭代
class Solution {
public int fib(int n) {
if(n == 0 || n == 1) return n;
//dp[i]: 第i个斐波拉契数 dp[i] = dp[i-1] + dp[i-2]
int[] dp = new int[n + 1];
dp[1] = 1;
for(int i = 2; i <= n; i ++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
}
二、递归
class Solution {
public int fib(int n) {
if(n == 0 || n == 1) return n;
return fib(n-1) + fib(n-2);
}
}