In this example, i’ll show you, How to generate pascals triangle for the given number using C#.
Pascal’s Triangle is a number pattern in the shape of a triangle. Pascal’s Triangle has many applications in mathematics and statistics, including its ability to help you calculate combinations.
Each number in the triangle is the sum of the two numbers above it. For example, row 4 − it’s the sum of 3 and 3 in the row above. The very first and very last number in any row are always going to be 1.
Time complexity − O(N)
Space complexity − O(N)
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class Arrays{ public List<List<int>> GeneratePascal(int n){ List<List<int>> res = new List<List<int>>(); if (n <= 0){ return null; } List<int> first = new List<int>(); first.Add(1); res.Add(first); if (n == 1){ return res; } for (int i = 2; i < n; i++){ List<int> prev = res.LastOrDefault(); List<int> cur = new List<int>(); for (int temp = 0; temp < i; temp++){ cur.Add(1); } for (int j = 1; j < i - 1; j++){ cur[j] = prev[j - 1] + prev[j]; } res.Add(cur); } return res; } } static void Main(string[] args){ Arrays s = new Arrays(); var res = s.GeneratePascal(5); } |
Output:
1 2 3 |
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] |