Pascal's Triangle

来源:互联网 发布:mysql update性能优化 编辑:程序博客网 时间:2024/06/11 11:40

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],即当前元素=正上方元素+左上方元素

P.S:欢迎各位学友都对我的解法的不足之处作出建议!

0 0