Pascal's Triangle

来源:互联网 发布:mac jenkins 启动 编辑:程序博客网 时间:2024/05/29 04:19

每日一题;

今天做的还是杨辉三角,不过今天的非常简单,还没来得及优化~有时间就换种思路来做。

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 List<List<Integer>> generate(int numRows) {        List<List<Integer>> results = new ArrayList<List<Integer>>();        if(numRows<0){            return null;        }        if(numRows == 0){            return results;        }        int[][] tri = new int[numRows][numRows];        tri[0][0] = 1;        for(int i=1;i<numRows;i++){            tri[i][0] = 1;            for(int j = 1;j<=i;j++){                tri[i][j] = tri[i-1][j-1]+tri[i-1][j];            }        }        for(int i = 0;i<numRows;i++){            ArrayList<Integer> temp = new ArrayList<Integer>();            for(int j = 0;j<=i;j++){                temp.add(tri[i][j]);            }            results.add(temp);        }        return results;    }}


0 0
原创粉丝点击