From 4db2e7e4cb7fc678a18b82eaa7d96237d06e0278 Mon Sep 17 00:00:00 2001 From: Divya pratap Singh <64465398+Divyapratap-369@users.noreply.github.com> Date: Tue, 24 Oct 2023 21:05:56 +0530 Subject: [PATCH] Create ClimbingStairs.java Climbing Stairs Question with proper comments and explanation --- algorithms/java/ClimbingStairs.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 algorithms/java/ClimbingStairs.java diff --git a/algorithms/java/ClimbingStairs.java b/algorithms/java/ClimbingStairs.java new file mode 100644 index 0000000..1371d21 --- /dev/null +++ b/algorithms/java/ClimbingStairs.java @@ -0,0 +1,22 @@ +class Solution { + public int climbStairs(int n) { + // Create an array to store the number of ways to climb each stair. + int[] dp = new int[n + 1]; + + // There is one way to climb 0 stairs (no steps). + dp[0] = 1; + + // There is one way to climb 1 stair (take 1 step). + dp[1] = 1; + + // Calculate the number of ways to climb each stair from 2 to n. + for (int i = 2; i <= n; i++) { + // The number of ways to reach the current stair is the sum of + // the ways to reach the previous two stairs. + dp[i] = dp[i - 1] + dp[i - 2]; + } + + // The final value in dp array (dp[n]) contains the answer. + return dp[n]; + } +}