[leetcode-118]Pascal's triangle 杨辉三角

Pascal's triangle

(1过)

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]
]

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

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
public class PascalTriangle {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (numRows <= 0) {
            return res;
        }

        for (int i=0;i<numRows;i++) {
            ArrayList<Integer> list = new ArrayList<>();
            list.add(1);
            for (int j=1;j<=i-1;j++) {
                list.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
            }
            if (i>=1) {
                list.add(1);
            }
            res.add(list);
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/twoheads/p/10566803.html