DEV Community

Miss Pooja Anilkumar Patel
Miss Pooja Anilkumar Patel

Posted on • Updated on

509. Leetcode solution in Cpp

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();
  }
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)