-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count possible ways to construct buildings.cpp
94 lines (86 loc) · 1.42 KB
/
Count possible ways to construct buildings.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
/*-----ALL POSSIBLE APPROACHES------*/
//RECURSION (TLE)
#define ll long long
int mod=1e9+7;
class Solution{
public:
int help(int i)
{
//base case
if(i<=0)
return 1;
//recursive calls
int a=help(i-1);
int b=help(i-2);
return (a+b)%mod;
}
int TotalWays(int N)
{
int ans=help(N);
return (1LL*ans*ans)%mod;
}
};
// MEMOIZATION
#define ll long long
int mod=1e9+7;
class Solution{
public:
int help(int i,vector<int>& memo)
{
//base case
if(i<=0)
return 1;
// memo check
if(memo[i]!=-1)
return memo[i];
//recursive calls
int a=help(i-1,memo);
int b=help(i-2,memo);
return memo[i]=(a+b)%mod;
}
int TotalWays(int N)
{
vector<int> memo(N+1,-1);
int ans=help(N,memo);
return (1LL*ans*ans)%mod;
}
};
// TABULATION
#define ll long long
int mod=1e9+7;
class Solution{
public:
int TotalWays(int N)
{
vector<int> dp(N+1,0);
dp[0]=1;
for(int i=1;i<=N;i++)
{
int a=dp[i-1];
int b=1;
if(i-2>=0)
b=dp[i-2];
dp[i]=(a+b)%mod;
}
int ans=dp[N];
return (1LL*ans*ans)%mod;
}
};
// SPACE OPTIMIZED
#define ll long long
int mod=1e9+7;
class Solution{
public:
int TotalWays(int N)
{
int a=1;
int b=1;
for(int i=1;i<=N;i++)
{
int curr=(a+b)%mod;
b=a;
a=curr;
}
return (1LL*a*a)%mod;
}
};