Pascal’s Triangle
要求
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
标签:Array
我的提交
public IList<IList<int>> Generate(int numRows) {
int[][] result = new int[numRows][];
for (int i = 0; i < numRows;i++ )
{
result[i] = new int[i + 1];
for(int j=0;j<=i;j++)
{
if (i == j || j == 0)
result[i][j] = 1;
else
{
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
}
}
return result;
}
注意事项:
- 外层循环:控制次数,次数=行数
- 每个内层循环开始前,需对该行申请足够空间
- 内层循环:
- 情况1:
j==0 || j==i
行首||行尾 - 结果1:置1
- 情况2:非行首行尾元素
- 结果2:
result[i][j]=result[i-1]+result[i-1][j-1]
,即当前元素=正上方元素+左上方元素
- 情况1:
P.S:欢迎各位学友都对我的解法的不足之处作出建议!