How to generate pascals triangle for the given number using C#?

CsharpServer Side ProgrammingProgramming

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

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],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
raja
Published on 17-Aug-2021 07:55:07
Advertisements