如何使用 C# 为给定数字生成帕斯卡三角形?

帕斯卡三角形是三角形形状的数字模式。帕斯卡三角在数学和统计学中有许多应用,包括它帮助您计算组合的能力。

三角形中的每个数字都是它上面的两个数字之和。例如,第 4 行 - 它是上一行中 3 和 3 的总和。任何行中的第一个和最后一个数字始终为 1。

时间复杂度-O(N)

空间复杂度-O(N)

示例

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);
}
输出结果
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]