From 123c4ef5d710c576d6c6b67bd8d28184be82fec1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 19 Jul 2022 16:26:56 +0200 Subject: [PATCH] problems: add pascals triangle Signed-off-by: Matej Focko --- problems/pascals-triangle.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 problems/pascals-triangle.cpp diff --git a/problems/pascals-triangle.cpp b/problems/pascals-triangle.cpp new file mode 100644 index 0000000..61ad1da --- /dev/null +++ b/problems/pascals-triangle.cpp @@ -0,0 +1,30 @@ +class Solution { + int getN(const vector& previousRow, int n) + { + if (n == 0 || n == previousRow.size()) { + return 1; + } + return previousRow[n - 1] + previousRow[n]; + } + +public: + vector> generate(int numRows) + { + if (numRows <= 0) { + return {}; + } + + vector> result { vector { 1 } }; + for (auto i = 2; i <= numRows; i++) { + auto& previous = result.back(); + vector current; + + for (auto j = 0; j < i; j++) { + current.push_back(getN(previous, j)); + } + result.push_back(move(current)); + } + + return result; + } +};