-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path119_PascalTriangle2.cpp
More file actions
109 lines (87 loc) · 2.02 KB
/
Copy path119_PascalTriangle2.cpp
File metadata and controls
109 lines (87 loc) · 2.02 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
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
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <map>
#include <vector>
#include <cmath>
#include <stdexcept>
template <typename S>
std::ostream &operator<<(std::ostream &os,
const std::vector<S> &vector)
{
// Printing all the elements
// using <<
for (auto element : vector)
{
os << element << " ";
}
return os;
}
/*
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Constraints:
0 <= rowIndex <= 33
*/
class Solution
{
private:
std::map<int, double> factorialMap;
double fact(int f)
{
double factorial = 1;
if (f <= 1)
{
return (factorial);
}
else
{
try
{
factorial = factorialMap.at(f);
}
catch (const std::out_of_range &oor)
{
for (int i = 1; i <= f; i++)
{
factorial *= i;
}
factorialMap.insert(std::pair<int, double>(f, factorial));
}
return (factorial);
}
return (factorial);
}
double nCk(int n, int k)
{
double result = ((fact(n) / fact(n - k)) / (fact(k)));
return result;
}
public:
std::vector<int> getRow(int rowIndex)
{
std::vector<int> pascalIntRow;
if (rowIndex > 31)
{
std::cout << "WARNING: Please keep numbers <=31.\n";
}
for (int i = 0; i <= rowIndex; i++)
{
pascalIntRow.push_back(round(nCk(rowIndex, i)));
}
return pascalIntRow;
}
};
int main()
{
Solution S1;
std::vector<int> pascalTriangle2 = S1.getRow(5);
std::cout << pascalTriangle2 << std::endl;
pascalTriangle2 = S1.getRow(32);
std::cout << pascalTriangle2 << std::endl;
return 0;
}