# Climbing Stairs

{% embed url="<https://leetcode.com/problems/climbing-stairs>" %}

## Solution 1

```java
class Solution {
    public int climbStairs(int n) {
        if (n <= 2) return n;
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        
        for (int i = 3; i < n + 1; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
}
```

The DP function is:

$$
dp\[i] = dp\[i-1] + dp\[i-2]
$$

`dp[i]` stands for the number of ways to reach the ith step. This number should be equal to the number of ways to reach the (i-1)th step plus the number of ways to reach the (i-2)th step. The reason is that one can only take 1 or 2 steps, so the ith step either comes from the (i-1)th step or the (i-2)th step.

Time complexity: `O(n)`

Space complexity: `O(n)`

## Solution 2

```java
class Solution {
    public int climbStairs(int n) {
        if (n <= 2) return n;
        int a = 1, b = 2, c = 3;
        for (int i = 0; i < n - 3; i++) {
            a = b;
            b = c;
            c = a + b;
        }
        return c;
    }
}

// a b c
//   a b c
//     a b c
// 1 2 3 5 8
```

It is not hard to tell that this DP function resembles the Fibonacci Number function. Then, we can use what we have in the [Fibonacci Number](/algo/dynamic-programming/fibonacci-number.md#solution-3) problem (use 3 variables to dynamically keep the results) to solve this problem.

Time complexity: `O(n)`

Space complexity: `O(1)`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yushunchen.com/algo/dynamic-programming/climbing-stairs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
