Recursion: Davis' Staircase Discussions | | HackerRank

Recursion: Davis' Staircase

  • + 0 comments

    Iterative implementaion with time complexity O(n) and space complexity O(1). Oddly enough, it passes without the % 10000000007.

    int stepPerms(int n)
    {
      vector<int> ring{1, 2, 4};
      if (n < 4) {
        return ring[n - 1];
      }
      int p = 2;
      for (int i = 4; i <= n; i++) {
        p = (p + 1) % 3;
        ring[p] = ring[0] + ring[1] + ring[2];
      }
    
      return ring[p];
    }