mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems: add pascals triangle
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
d1e2d4a9cf
commit
123c4ef5d7
1 changed files with 30 additions and 0 deletions
30
problems/pascals-triangle.cpp
Normal file
30
problems/pascals-triangle.cpp
Normal file
|
@ -0,0 +1,30 @@
|
|||
class Solution {
|
||||
int getN(const vector<int>& previousRow, int n)
|
||||
{
|
||||
if (n == 0 || n == previousRow.size()) {
|
||||
return 1;
|
||||
}
|
||||
return previousRow[n - 1] + previousRow[n];
|
||||
}
|
||||
|
||||
public:
|
||||
vector<vector<int>> generate(int numRows)
|
||||
{
|
||||
if (numRows <= 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
vector<vector<int>> result { vector<int> { 1 } };
|
||||
for (auto i = 2; i <= numRows; i++) {
|
||||
auto& previous = result.back();
|
||||
vector<int> current;
|
||||
|
||||
for (auto j = 0; j < i; j++) {
|
||||
current.push_back(getN(previous, j));
|
||||
}
|
||||
result.push_back(move(current));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue