LeetCode-118-Pascal's Triangle(帕斯卡的三角形)

来源:互联网 发布:饥饿游戏知乎 编辑:程序博客网 时间:2024/05/17 08:03

Q:

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

Analysis:

基础的算法问题,中间元素值等于“肩上”两元素之和。

Code:

class Solution {    public List<List<Integer>> generate(int numRows) {        List<List<Integer>> out = new ArrayList<List<Integer>>();        if (numRows == 0) {            return out;        } else {            for (int i = 1; i <= numRows; i++) {                ArrayList<Integer> in = new ArrayList<Integer>();                for (int j = 0; j < i; j++) {                    if (j == 0 || j == i - 1) {                        in.add(1);                    } else {                        in.add(out.get(i - 2).get(j - 1) + out.get(i - 2).get(j));                    }                }                out.add(in);            }        }        return out;    }}
原创粉丝点击