-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathLadder.cpp
99 lines (91 loc) · 1.62 KB
/
Ladder.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
using namespace std;
// topdown
int solve(int n, int k)
{
if (n == 0)
{
return 1;
}
if (n < 0)
{
return 0;
}
int ans = 0;
for (int i = 1; i <= k; i++)
{
ans += solve(n - i, k);
}
return ans;
}
// topdown optimised
int solvetd(int n, int k, int *dp)
{
if (n == 0)
{
return 1;
}
if (n < 0)
{
return 0;
}
if (dp[n] != 0)
{
return dp[n];
}
int ans = 0;
for (int i = 1; i <= k; i++)
{
ans += solvetd(n - i, k, dp);
}
return dp[n] = ans;
}
// bottomUp
int bottomup(int n, int k)
{
int dp[1000] = {0};
int ans = 0;
dp[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= k; j++)
{
if ((i - j) >= 0)
{
dp[i] += dp[i - j];
}
}
}
return dp[n];
}
// bottomUp Optimise
int bottomUpOptimise(int n, int k)
{
int dp[1000] = {0};
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++)
{
if ((i - (k + 1)) < 0)
dp[i] = (2 * dp[i - 1]);
else
dp[i] = (2 * dp[i - 1]) - dp[i - (k + 1)];
}
return dp[n];
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int dp[1000] = {0};
cout << "topdown " << solve(n, k) << endl;
cout << "topdown optimise " << solvetd(n, k, dp) << endl;
cout << "bottomup " << bottomup(n, k) << endl;
cout << "bottomup optimise " << bottomUpOptimise(n, k) << endl;
cout << endl;
}
return 0;
}