You are climbing a staircase. It takes n 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
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top
Example:
Input: n=8
Output: 34
Approach
Java
public class ClimbingStairs {public static void main(String[] args) {int n = 8;int ways = climbStairs(n);System.out.println(ways);}// function to the number// of ways to reach to the top// of stairsprivate static int climbStairs(int n) {int dp[] = new int[n + 1];if (n == 0)return 1;dp[0] = 1;dp[1] = 1;if (n == 1)return dp[1];// we move either 1 or 2 stepsfor (int i = 2; i <= n; i++)dp[i] = dp[i - 1] + dp[i - 2];return dp[n];}}
C++
#include <bits/stdc++.h>using namespace std;//function to the number//of ways to reach to the top//of stairsint climbStairs(int n){int dp[n+1];if(n==0)return 1;dp[0]=1;dp[1]=1;if(n==1)return dp[1];//we move either 1 or 2 stepsfor(int i=2;i<=n;i++)dp[i]=dp[i-1]+dp[i-2];return dp[n];}int main(){int n=8;int ways=climbStairs(n);cout<<ways<<"\n";return 0;}
No comments:
Post a Comment