leetcode--Pascal's Triangle

来源:互联网 发布:linux终端 java安装 编辑:程序博客网 时间:2024/05/16 15:57

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

题意:如图,求帕斯卡三角形

分类:数组


解法1:逐行求即可。

public class Solution {    public List<List<Integer>> generate(int numRows) {        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();        for(int i=1;i<=numRows;i++){            ArrayList<Integer> t = new ArrayList<Integer>();            t.add(1);            for(int j=1;j<i-1;j++){                t.add(res.get(i-2).get(j-1)+res.get(i-2).get(j));            }            if(i!=1) t.add(1);            res.add(t);        }        return res;    }}

0 0
原创粉丝点击