Skip to content

Commit b8aa4ac

Browse files
authored
118. Pascal's Triangle (#120)
1 parent 39a392f commit b8aa4ac

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@
9191
| 113 | Path Sum II | [Ruby](./algorithms/ruby/0113-path-sum-ii.rb) | Medium |
9292
| 114 | Flatten Binary Tree to Linked List | [Ruby](./algorithms/ruby/0114-flatten-binary-tree-to-linked-list.rb) | Medium |
9393
| 117 | Populating Next Right Pointers in Each Node II | [Ruby](./algorithms/ruby/0117-populating-next-right-pointers-in-each-node-ii.rb) | Medium |
94+
| 118 | Pascal's Triangle | [Ruby](./algorithms/ruby/0118-pascals-triangle.rb) | Easy |
9495
| 120 | Triangle | [Ruby](./algorithms/ruby/0120-triangle.rb) | Medium |
9596
| 121 | Best Time to Buy and Sell Stock | [Ruby](./algorithms/ruby/0121-best-time-to-buy-and-sell-stock.rb) | Easy |
9697
| 122 | Best Time to Buy and Sell Stock II | [Ruby](./algorithms/ruby/0122-best-time-to-buy-and-sell-stock-ii.rb) | Medium |
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# frozen_string_literal: true
2+
3+
# 118. Pascal's Triangle
4+
# Easy
5+
# https://leetcode.com/problems/pascals-triangle
6+
7+
=begin
8+
Given an integer numRows, return the first numRows of Pascal's triangle.
9+
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
10+
11+
Example 1:
12+
Input: numRows = 5
13+
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
14+
15+
Example 2:
16+
Input: numRows = 1
17+
Output: [[1]]
18+
19+
Constraints:
20+
* 1 <= numRows <= 30
21+
=end
22+
23+
# @param {Integer} num_rows
24+
# @return {Integer[][]}
25+
def generate(num_rows)
26+
result = [[1]]
27+
28+
(num_rows - 1).times do
29+
prev_row = result.last
30+
row = [1]
31+
32+
0.upto(prev_row.size - 2) do |i|
33+
row << prev_row[i] + prev_row[i + 1]
34+
end
35+
36+
row << 1
37+
result << row
38+
end
39+
40+
result
41+
end
42+
43+
# **************** #
44+
# TEST #
45+
# **************** #
46+
47+
require "test/unit"
48+
class Test_generate < Test::Unit::TestCase
49+
def test_
50+
assert_equal [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]], generate(5)
51+
assert_equal [[1]], generate(1)
52+
end
53+
end

0 commit comments

Comments
 (0)