C#交错数组(jag array)实现的杨辉三角算法
——————————————————————————————————-
static void YHTriangle(int LineNums)
{
int N = LineNums;
if (0 >= N)
{
Console.WriteLine(“You must input a positive interger!”);
return;
}
int[][] myArray = new int[N][]; //定义一个交错数组
//给第一行赋值
myArray[0] = new int[1];
myArray[0][0] = 1;
//给第2–n行赋值
for (int i = 1; i < N; i++)
{
myArray[i] = new int[i + 1];
myArray[i][0] = 1;
myArray[i][i] = 1;
for (int j = 1; j < i; j++)
{
myArray[i][j] = myArray[i – 1][j – 1] + myArray[i – 1][j];
}
}
for (int i = 0; i < N; i++)
{
//在每行开始输出n-i-1个空格
string space = string.Empty;
for (int k = 0; k < n – i; k++)
space += ” “;
Console.Write(“{0}”,space);
//输出每一行的数字
for (int j = 0; j<=i; j++)
{
Console.Write(“{0} “, myArray[i][j]);
}
Console.WriteLine();
}
Console.ReadLine();
}