Why this cpp solution only beats 3%, how can be much faster?


  • 0
    Y
    class Solution {
    public:
        int climbStairs(int n) {
            if (n == 0) return 0;
            if (n == 1) return 1;
            if (n == 2) return 2;
            int res[2] = {1, 2};
            int idx = 1;
            int dir = -1;
            for (int i = 2; i < n; i++) {
              idx += dir;
              res[idx] = res[0] + res[1];
              dir = -dir;
            }
            return res[0] > res[1] ? res[0] : res[1];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.