public static int f1(int n) { if (n < 1) { return 0; } if (n == 1 || n == 2) { return 1; } return f1(n - 1) + f1(n - 2); }
O(n)复杂度的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public static int f2(int n) { if (n < 1) { return 0; } if (n == 1 || n == 2) { return 1; } int res = 1; int pre = 1; int tmp = 0; for (int i = 3; i <= n; i++) { tmp = res; res = res + pre; pre = tmp; } return res; }
public static int s1(int n) { if (n < 1) { return 0; } if (n == 1 || n == 2) { return n; } return s1(n - 1) + s1(n - 2); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
public static int s2(int n) { if (n < 1) { return 0; } if (n == 1 || n == 2) { return n; } int res = 2; int pre = 1; int tmp = 0; for (int i = 3; i <= n; i++) { tmp = res; res = res + pre; pre = tmp; } return res; }
public static int c2(int n) { if (n < 1) { return 0; } if (n == 1 || n == 2 || n == 3) { return n; } int res = 3; int pre = 2; int prepre = 1; int tmp1 = 0; int tmp2 = 0; for (int i = 4; i <= n; i++) { tmp1 = res; tmp2 = pre; res = res + prepre; pre = tmp1; prepre = tmp2; } return res; }