给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

    118. 杨辉三角 - 图1
    在杨辉三角中,每个数是它左上方和右上方的数的和。
    示例:

    输入: 5 输出: [

    1. [1],
    2. [1,1],

    [1,2,1],

    [1,3,3,1],

    [1,4,6,4,1]

    ]

    思路:

    根据动图描述暴力求解 用两个循环,一个循环控制行数,一个循环控制列数 如果是开始或者结尾的数就直接赋值为1,如果不是就如同动图所示,找到对应位置的数据相加再赋值;

    1. class Solution {
    2. public List<List<Integer>> generate(int numRows) {
    3. List<List<Integer>> result = new ArrayList<>();
    4. for (int i = 1; i <= numRows; i++) {
    5. List<Integer> row = new ArrayList<>();
    6. int next = 0;
    7. for (int j = 1; j <= i; j++) {
    8. if (j == 1 || j == i){
    9. row.add(1);
    10. }else {
    11. row.add(result.get(i - 2).get(next) + result.get(i - 2).get(next + 1));
    12. next ++;
    13. }
    14. }
    15. result.add(row);
    16. }
    17. return result;
    18. }
    19. }