Leetcode
  • Leetcode
  • 1. Two Sum
  • 7. Reverse Integer
  • 9. Palindrome Number
  • 13. Roman to Integer
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 35. Search Insert Position
  • 53. Maximum Subarray
  • 58. Length of Last Word
  • 66. Plus One
  • 876. Middle of the Linked List
  • 67. Add Binary
  • 69. Sqrt(x)
  • 83. Remove Duplicates from Sorted List
  • 14. Longest Common Prefix
  • 70. Climbing Stairs
  • 100. Same Tree
  • 101. Symmetric Tree
  • 104. Maximum Depth of Binary Tree
  • Untitled
Powered by GitBook
On this page

70. Climbing Stairs

Previous14. Longest Common PrefixNext100. Same Tree

Last updated 6 years ago

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Solution:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        def choose(n, x):
            nl = 1
            for i in range(1, n+1, 1):
                nl *= i
            xl = 1
            for i in range(1, x+1, 1):
                xl *= i
            n_xl = 1
            for i in range(1, n-x+1, 1):
                n_xl *= i
            return nl/xl/n_xl
            
        num = 0
        for i in range(n/2+1):
            num += choose(n-i, i)
        return num
https://leetcode.com/problems/climbing-stairs/description/