Pascal's Triangle-LeetCode#118

118. Pascal’s Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

思路:给定非负整数numRows,生成Pascal三角形的第一个numRows。在Pascal的三角形中,每个数字是它正上方的两个数字的总和。从图中可以得出首尾数字都为1,中间数字res[i][j] = res[i-1][j-1] + res[i-1][j]
代码如下:

public class PascalTriangle {
    public static List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            List<Integer> temp = new ArrayList<>();
            if (i == 0) {
                temp.add(1);
            } else {
                for (int j = 0; j < i + 1; j++) {
                    if (j == 0) {
                        temp.add(1);
                    } else if (j == i) {
                        temp.add(1);
                    } else {
                        temp.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
                    }
                }
            }
            res.add(temp);
        }
        return res;
    }
}
文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部