斐波那契数 方法一:递推(动态规划) class Solution { public: int fib(int n) { if (n < 2) { return n; } int p = 0, q = 0, r = 1; for (int i = 2; i <= n; ++i) { p = q; q = r; r = p + q; } return r; } }; 方法二:通项公式 class Solution { public: int fib(int n) { double sqrt5 = sqrt(5); double fibN = pow((1 + sqrt5) / 2, n) - pow((1 - sqrt5) / 2, n); return round(fibN / sqrt5); } }; 第N个泰斐波那锲数 class Solution { public: int tribonacci(int n) { int a = 0, b = 1, c = 1; if (n == 0) return a; else if (n == 1 || n == 2) return b; else { int k = n - 2, t; while (k -- ) { t = a + b + c; a = b, b = c, c = t; } return t; } } };