Fibonacci numbers
思路
/**
* Created by yang on 1/1/17.
*/
public class Solution {
// method1: recusion
public static int fib1(int n) {
if (n <= 1) return n;
return fib1(n - 1) + fib1(n - 2);
}
// method2: dp
public static int fib2(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// method 3: optimize space
public static int fib3(int n) {
int[] dp = new int[2];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
int tmp = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = tmp;
}
return dp[1];
}
public static void main(String[] args) {
System.out.println(fib3(9));
}
}Last updated