Skip to content

Commit f6fc536

Browse files
authored
update files
1 parent d91cf16 commit f6fc536

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

pascalsTriangle/PascalsTriangle.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
# Pascal's Triangle - LeetCode Solution 🚀
3+
4+
## Problem Statement
5+
Given an integer `numRows`, return the first `numRows` of Pascal's triangle.
6+
7+
## Approach
8+
9+
To generate Pascal's Triangle, follow these steps:
10+
11+
1. **Initialization**:
12+
- Create a 2D vector `result` to store the rows of Pascal's Triangle.
13+
14+
2. **Iterate through the rows**:
15+
- Loop from `0` to `numRows - 1` to generate each row.
16+
- For each row `i`, initialize a vector `row` with `i + 1` elements, all set to `1` because the first and last elements of each row are always `1`.
17+
18+
3. **Fill in the values**:
19+
- For each element `j` in the row, except for the first and last elements, set `row[j]` to the sum of the two elements directly above it from the previous row:
20+
\[
21+
row[j] = result[i - 1][j - 1] + result[i - 1][j]
22+
\]
23+
24+
4. **Add the row to the result**:
25+
- Append the fully populated row to the `result` vector.
26+
27+
5. **Return the result**:
28+
- After generating all rows, return the `result` vector.
29+
30+
### Time Complexity ⏱️
31+
- The time complexity is **O(numRows^2)** because we are iterating through each element of each row once.
32+
33+
### Space Complexity 💾
34+
- The space complexity is **O(numRows^2)** due to the space required to store the entire triangle in memory.
35+
36+
## Code Implementation in C++
37+
38+
```cpp
39+
class Solution {
40+
public:
41+
vector<vector<int>> generate(int numRows) {
42+
std::vector<std::vector<int>> result;
43+
for(int i=0; i < numRows; i++){
44+
std::vector<int> row(i + 1, 1);
45+
for(int j = 1; j < i; j++){
46+
row[j] = result[i - 1][j - 1] + result[i - 1][j];
47+
}
48+
result.push_back(row);
49+
}
50+
return result;
51+
}
52+
};
53+
```
54+
55+
### LeetCode Performance 💯
56+
- **Time Complexity**: `0ms` (As fast as possible)
57+
- **Space Complexity**: `0ms` (Optimal memory usage)
58+
59+
> 🚀 **Conclusion**: This solution efficiently generates Pascal's Triangle with minimal time and space complexity. Enjoy coding!
60+
61+
---
62+
63+
**Keep Coding!** 💻✨
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> generate(int numRows) {
4+
std::vector<std::vector<int>> result;
5+
for(int i=0; i < numRows; i++){
6+
std::vector<int> row(i + 1, 1);
7+
for(int j = 1; j < i; j++){
8+
row[j] = result[i - 1][j - 1] + result[i - 1][j];
9+
}
10+
result.push_back(row);
11+
}
12+
return result;
13+
}
14+
};
15+

0 commit comments

Comments
 (0)