-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathctci-recursive-staircase.cpp
More file actions
55 lines (44 loc) · 918 Bytes
/
Copy pathctci-recursive-staircase.cpp
File metadata and controls
55 lines (44 loc) · 918 Bytes
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
// Recursion: Davis' Staircase
// Find the number of ways to get from the bottom of a staircase to the top if you can jump 1, 2, or 3 stairs at a time.
//
// https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem
//
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
// nota: le testcase max est n=36
// et ça tient dans un int 32-bit
map<int, int> cache;
int staircase(int n)
{
int nb = 0;
if (n == 0)
return 1;
auto i = cache.find(n);
if (i != cache.end())
{
return i->second;
}
for (int i = 1; i <= 3; ++i)
{
if (n >= i)
nb += staircase(n - i);
}
cache[n] = nb;
return nb;
}
int main() {
int q;
cin >> q;
while (q--)
{
int n;
cin >> n;
cout << staircase(n) << endl;
}
return 0;
}