LeetCode|Pascal's Triangle-java

来源:互联网 发布:淘宝上旗舰店是真的吗 编辑:程序博客网 时间:2024/04/29 10:43

题目:

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]]
思路:

给出行数,返回一个杨辉三角。

public class Solution {   public static List<List<Integer>> generate(int numRows) {        List<List<Integer>> result = new ArrayList<List<Integer>>(numRows);        if (numRows == 0) {            return result;        }        ArrayList<Integer> first = new ArrayList<Integer>();        for (int n = 0; n < numRows; n++) {            ArrayList<Integer> thisRow = new ArrayList<Integer>();            thisRow.add(1);            if (n > 0) {                List<Integer> previousRow = result.get(n - 1);                for (int i = 1; i < n; i++) {                    thisRow.add(previousRow.get(i - 1) + previousRow.get(i));                }                thisRow.add(1);            }            result.add(thisRow);        }        return result;    }}


0 0
原创粉丝点击