0ms C solution without using recursion, easy to understand


  • 0

    It just a Fibonacci sequence : (0),(1),1,2,3,5,8,13,21,34 ......
    We can find An = An-1 + An-2

    int climbStairs(int n) {
        int cnt = 2;
        int first = 1 , second = 2;
        int sum;
    
        if( n == first) return first;
        else if(n == second) return second;
        else {
            while(cnt < n){
                sum = first + second;
                first = second;
                second = sum;
                cnt++;
            }
            return sum;
        }
    }

Log in to reply
 

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