From 3e32d1c4645d2249ba1af47b879766b3fb100e52 Mon Sep 17 00:00:00 2001 From: Arpan Biswas <99377659+Geeks-Arpan@users.noreply.github.com> Date: Sat, 21 Oct 2023 08:03:39 +0530 Subject: [PATCH] Create Climbing_Stairs --- questions/java/Climbing_Stairs | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 questions/java/Climbing_Stairs diff --git a/questions/java/Climbing_Stairs b/questions/java/Climbing_Stairs new file mode 100644 index 0000000..ce1fe60 --- /dev/null +++ b/questions/java/Climbing_Stairs @@ -0,0 +1,62 @@ +// Using Recursion + +class stairs { + // A simple recursive program to find + // n'th fibonacci number + static int fib(int n) + { + if (n <= 1) + return n; + return fib(n - 1) + fib(n - 2); + } + + // Returns number of ways to reach s'th stair + static int countWays(int s) { return fib(s + 1); } + + /* Driver program to test above function */ + public static void main(String args[]) + { + int s = 4; + System.out.println("Number of ways = " + + countWays(s)); + } +} + +//Time Complexity: O(2n) +//Auxiliary Space: O(n) + +// Using Dynamic Programming + + +// Java program to count number of +// ways to reach Nth stair +class GFG { + + // A simple recursive function to find number of ways to + // reach the nth stair + static int countWays(int n, int dp[]) + { + if (n <= 1) + return dp[n] = 1; + + if (dp[n] != -1) { + return dp[n]; + } + dp[n] = countWays(n - 1, dp) + countWays(n - 2, dp); + return dp[n]; + } + + // Driver code + public static void main(String[] args) + { + int n = 4; + int[] dp = new int[n + 1]; + for (int i = 0; i < n + 1; i++) { + dp[i] = -1; + } + System.out.println(countWays(n, dp)); + } +} + +//Time Complexity: O(n) +//Auxiliary Space: O(n)