Climbing Staircase

Problem

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

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

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 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

Constraints:

  • 1 <= n <= 45

Solution

I remember doing this problem during undergrad/when studying for my AWS internship interviews. I remember the solution being pretty simple after discovering it. I know that it involves dynamic programming (this problem is in the DP category after all).

class Solution {
    public int climbStairs(int n) {
        return climbStairs(n, new HashMap<>());
    }

    public int climbStairs(int n, Map<Integer, Integer> m) {
        if (n < 3) {
            return n;
        }
        if (!m.containsKey(n)) {
            m.put(n, climbStairs(n - 1, m) + climbStairs(n - 2, m));
        }

        return m.get(n);
    }
}

Recent posts from blogs that I like

The artist who died alongside Scott

A physician, zoologist and ornithologist, and talented painted, he was in Antarctic in 1902-03, then returned in 1910-12, when he died trying to return from the South Pole.

via The Eclectic Light Company

Don't diagnose your opponents

When you disagree with someone, there are two paths forward. The first is to try to engage with what they’re saying: what their reasons are, whether their position is true, what evidence could be brought to bear, and so on. The second is to diagnose them: to engage with the second-order question of ...

via Sean Goedecke

FBI Arrests Executive at Ransomware Negotiation Firm

Agents with the Federal Bureau of Investigation (FBI) on Thursday arrested the co-founder of a Canadian cybersecurity firm in connection with an investigation into the ShinyHunters hacking group that recently relieved the FBI of sensitive data on thousands of agents, multiple sources tell KrebsOnSec...

via Krebs on Security