Python solution with detailed explanation


  • 0
    G

    Solution

    Climbing Stairs https://leetcode.com/problems/climbing-stairs/?tab=Description

    Dynamic Programming

    • n = 0,1 ways = 1
    • n = 2 ways = countways(1) + count(0) i.e. take 1 step or 2 steps.
    class Solution(object):
        def climbStairs(self, N):
            """
            :type n: int
            :rtype: int
            """
            if N <= 1:
                return 1
            prev_prev, prev, ways = 1, 1, 0
            for i in range(2, N+1):
                ways = prev + prev_prev
                prev_prev, prev = prev, ways
            return ways
    

Log in to reply
 

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