mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 09:45:04 +08:00
Add climbing stairs (#4168)
This commit is contained in:
@ -0,0 +1,30 @@
|
|||||||
|
package com.thealgorithms.dynamicprogramming;
|
||||||
|
|
||||||
|
/* A DynamicProgramming solution for Climbing Stairs' problem Returns the
|
||||||
|
distinct ways can you climb to the staircase by either climbing 1 or 2 steps.
|
||||||
|
|
||||||
|
Link : https://medium.com/analytics-vidhya/leetcode-q70-climbing-stairs-easy-444a4aae54e8
|
||||||
|
*/
|
||||||
|
public class ClimbingStairs {
|
||||||
|
|
||||||
|
public static int numberOfWays(int n) {
|
||||||
|
|
||||||
|
if(n == 1 || n == 0){
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
int prev = 1;
|
||||||
|
int curr = 1;
|
||||||
|
|
||||||
|
int next;
|
||||||
|
|
||||||
|
for(int i = 2; i <= n; i++){
|
||||||
|
next = curr+prev;
|
||||||
|
prev = curr;
|
||||||
|
|
||||||
|
curr = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
return curr;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.thealgorithms.dynamicprogramming;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
|
||||||
|
public class climbStairsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void climbStairsTestForTwo(){assertEquals(2, ClimbingStairs.numberOfWays(2));}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void climbStairsTestForZero(){assertEquals(0, ClimbingStairs.numberOfWays(0));}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void climbStairsTestForOne(){assertEquals(1, ClimbingStairs.numberOfWays(1));}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void climbStairsTestForFive(){assertEquals(8, ClimbingStairs.numberOfWays(5));}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void climbStairsTestForThree(){assertEquals(3, ClimbingStairs.numberOfWays(3));}
|
||||||
|
}
|
Reference in New Issue
Block a user