24. Pascal Triangle
The problem can be found at the following link: Question Link
My Approach
To generate the nth row of Pascal's Triangle, I optimize the simple brute force approach as follows:
I initialize two vectors,
out
andprev
, both of size n, with all elements set to 1.I iterate through each row, updating the elements of
out
based on the sum of the two corresponding elements from theprev
vector.I also use modular arithmetic to prevent integer overflow.
In each iteration, I update the
out
array with the values from theprev
array.
Explain with Example
For example, let's generate the 5th row of Pascal's Triangle:
Time and Auxiliary Space Complexity
Time Complexity:
O(n^2)
, wheren
is the number of rows.Auxiliary Space Complexity:
O(n)
, as I use two vectors of sizen
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated