mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-13 08:01:03 +01:00
Merge pull request #157 from TheAlgorithms/pascal-triangle-ii-math-approach
This commit is contained in:
commit
3ec899cc9c
2 changed files with 46 additions and 0 deletions
|
@ -103,6 +103,7 @@
|
|||
* [Find Min](https://github.com/TheAlgorithms/Ruby/blob/master/maths/find_min.rb)
|
||||
* [Lucas Series](https://github.com/TheAlgorithms/Ruby/blob/master/maths/lucas_series.rb)
|
||||
* [Number Of Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/number_of_digits.rb)
|
||||
* [Pascal Triangle Ii](https://github.com/TheAlgorithms/Ruby/blob/master/maths/pascal_triangle_ii.rb)
|
||||
* [Power Of Two](https://github.com/TheAlgorithms/Ruby/blob/master/maths/power_of_two.rb)
|
||||
* [Prime Number](https://github.com/TheAlgorithms/Ruby/blob/master/maths/prime_number.rb)
|
||||
* [Roman To Integer](https://github.com/TheAlgorithms/Ruby/blob/master/maths/roman_to_integer.rb)
|
||||
|
|
45
maths/pascal_triangle_ii.rb
Normal file
45
maths/pascal_triangle_ii.rb
Normal file
|
@ -0,0 +1,45 @@
|
|||
# Given an integer row_index, return the rowIndexth (0-indexed) row of the Pascal's triangle.
|
||||
|
||||
# Example 1:
|
||||
#
|
||||
# Input: row_index = 3
|
||||
# Output: [1,3,3,1]
|
||||
#
|
||||
# Example 2:
|
||||
#
|
||||
# Input: row_index = 0
|
||||
# Output: [1]
|
||||
#
|
||||
# Example 3:
|
||||
#
|
||||
# Input: row_index = 1
|
||||
# Output: [1,1]
|
||||
|
||||
# Complexity Analysis
|
||||
#
|
||||
# Time complexity: O(k).
|
||||
# Space complexity: O(k).
|
||||
|
||||
def get_row(row_index)
|
||||
(0..row_index).map {|num| combination(row_index, num) }
|
||||
end
|
||||
|
||||
def combination(num1, num2)
|
||||
factorial(num1) / (factorial(num2) * factorial(num1 - num2))
|
||||
end
|
||||
|
||||
def factorial(num)
|
||||
(1..num).inject(1) { |res, i| res * i }
|
||||
end
|
||||
|
||||
row_index = 3
|
||||
print(get_row(row_index))
|
||||
# => [1,3,3,1]
|
||||
|
||||
row_index = 0
|
||||
print(get_row(row_index))
|
||||
# => [1]
|
||||
|
||||
row_index = 1
|
||||
print(get_row(row_index))
|
||||
# => [1,1]
|
Loading…
Reference in a new issue