Pascal's Triangle

来源:互联网 发布:import form js 编辑:程序博客网 时间:2024/06/06 12:31
Problem:

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

杨辉三角。
Solution:
public class Solution {
    public List<List<Integer>> generate(int numRows) {
     List<List<Integer>> result = new ArrayList<>();
     if(numRows<=0)
         return result;
    
     ArrayList<Integer> list = new ArrayList<>();
     list.add(1);
     result.add(list);
     for (int i = 1; i < numRows; i++) {
        list = new ArrayList<>();
        for(int j=0;j<=i;j++)
        {
            if(j==0||j==i)
                list.add(1);
            else
                list.add(result.get(i-1).get(j-1)+result.get(i-1).get(j));
        }
        result.add(list);
    }
    
     return result;
   }
}
0 0