Skip to content

Commit abfaaf6

Browse files
committed
Add pascals triangle
1 parent 998f3a3 commit abfaaf6

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

Easy/pascals-triangle.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
Code
2+
====
3+
4+
```go
5+
func generate(numRows int) [][]int {
6+
sol := make([][]int, numRows)
7+
for i := 1; i <= numRows; i++ {
8+
row := make([]int, i)
9+
row[0] = 1
10+
row[i-1] = 1
11+
sol[i-1] = row
12+
}
13+
14+
for i, row := range sol {
15+
for j, val := range row {
16+
if val == 0 {
17+
sol[i][j] = sol[i-1][j] + sol[i-1][j-1]
18+
}
19+
}
20+
}
21+
22+
return sol
23+
}
24+
```
25+
26+
Solution in mind
27+
================
28+
29+
- Solution slice has `rows = numRows`. hence we initialise `sol` to have that many rows (int slices).
30+
31+
- Each row (`int slice`) will have elements equal to the row's position. That is, ith row will have i elements in it.
32+
33+
- In these i elements, the first and last are always 1. After we set this, initialisation is complete.
34+
35+
- Next we iterate through elements in every row. If the element's value is 1, it stays that way, if it is 0, it's value must be computed using it's parents (element above and element above and one place left).
36+
37+
- Post the iteration, the triangle will be filled.

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ Link to profile, [bhargavsnv100](https://leetcode.com/bhargavsnv100/)
77

88
| [Easy](#easy) | [Medium](#medium) | [Hard](#hard) |
99
|---------------|-------------------|---------------|
10-
| 40 | 68 | 12 |
10+
| 41 | 68 | 12 |
1111

1212
Problems finished
1313
=================
@@ -95,6 +95,8 @@ Easy
9595

9696
- [average-of-levels-in-binary-tree](Easy/average-of-levels-in-binary-tree.md)
9797

98+
- [pascals-triangle](Easy/pascals-triangle.md)
99+
98100
Medium
99101
------
100102

0 commit comments

Comments
 (0)