Posts Stairs
Post
Cancel

Stairs

Problem Description

You are climbing a staircase and it takes A 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?
Return the number of distinct ways modulo 1000000007

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {

    int M = 1000000007;

    public int climbStairs(int A) {

        int[] dp = new int[A+1];
        dp[0] = 1;
        dp[1] = 1;

        return climbStairsHelper(A, dp);

    }

    public int climbStairsHelper(int N, int[] dp){

        if(N == 0 || N == 1) return 1;

        if(dp[N] == 0){
            dp[N] = (climbStairsHelper(N-1, dp)%M + climbStairsHelper(N-2, dp)%M)%M;
        }

        return dp[N];

    }
}

This post is licensed under CC BY 4.0 by the author.