Pascal's Triangle

来源:互联网 发布:mac mt4交易平台 编辑:程序博客网 时间:2024/06/11 17:18

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 ArrayList<ArrayList<Integer>> generate(int numRows) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();                for(int i=0; i<numRows; i++) {            result.add(new ArrayList<Integer>());            if(i == 0) {                result.get(0).add(1);            }            else if(i == 1) {                result.get(1).add(1);                result.get(1).add(1);            }            else {                for(int j=0; j<=i; j++) {                    if(j==0 || j==i) {                        result.get(i).add(1);                    }                    else {                        result.get(i).add(result.get(i-1).get(j-1) + result.get(i-1).get(j));                    }                }            }        }                return result;    }}

0 0