Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Climbing_Stairs #244

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions questions/java/Climbing_Stairs
Original file line number Diff line number Diff line change
@@ -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)