Skip to content

509. Fibonacci Number 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int fib(int N) {
    if (N < 2)
      return N;

    vector<int> dp{0, 0, 1};

    for (int i = 2; i <= N; ++i) {
      dp[0] = dp[1];
      dp[1] = dp[2];
      dp[2] = dp[0] + dp[1];
    }

    return dp.back();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int fib(int N) {
    if (N < 2)
      return N;

    int[] dp = {0, 0, 1};

    for (int i = 2; i <= N; ++i) {
      dp[0] = dp[1];
      dp[1] = dp[2];
      dp[2] = dp[0] + dp[1];
    }

    return dp[2];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def fib(self, N: int) -> int:
    if N < 2:
      return N

    dp = [0, 0, 1]

    for i in range(2, N + 1):
      dp[0] = dp[1]
      dp[1] = dp[2]
      dp[2] = dp[0] + dp[1]

    return dp[2]