-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion-davis-staircase.java
More file actions
74 lines (54 loc) · 1.72 KB
/
recursion-davis-staircase.java
File metadata and controls
74 lines (54 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Davis has staircases in his house and he likes to climb each staircase , , or steps at a time. Being a very precocious child, he wonders how many ways there are to reach the top of the staircase.
Given the respective heights for each of the staircases in his house, find and print the number of ways he can climb each staircase on a new line.
Input Format
The first line contains a single integer, , denoting the number of staircases in his house.
Each line of the subsequent lines contains a single integer, , denoting the height of staircase .
Constraints
Subtasks
for of the maximum score.
Output Format
For each staircase, print the number of ways Davis can climb it in a new line.
Sample Input
3
1
3
7
Sample Output
1
4
44
*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for(int a0 = 0; a0 < s; a0++){
int n = in.nextInt();
System.out.println(countWays(n, m));
}
}
public static int countWays(int stairs, Map<Integer, Integer> mem) {
if (mem.containsKey(stairs)) {
return mem.get(stairs);
}
if (stairs == 1) {
return 1;
}
if (stairs == 2) {
return 2;
}
if (stairs == 3) {
return 4;
}
int ways = countWays(stairs - 1, mem) + countWays(stairs - 2, mem) + countWays(stairs - 3, mem);
mem.put(stairs, ways);
return ways;
}
}