Pascal's Triangle (Java)

来源:互联网 发布:古巴网络 编辑:程序博客网 时间:2024/06/13 09:15
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]

]


Source

public static List<List<Integer>> generate(int numRows){    List<List<Integer>> s = new ArrayList<List<Integer>>();    if(numRows == 0) return s;    ArrayList<Integer> a = new ArrayList<Integer>();    a.add(1);       s.add(a);//注意二维的赋值问题 不能直接添加1    for(int i = 1; i < numRows; i++){    List<Integer> t = new ArrayList<Integer>();    t.add(1);    for(int j = 1; j <= i - 1 ; j++){    t.add(s.get(i - 1).get(j - 1) + s.get(i - 1).get(j));    }    t.add(1);    s.add(t);    }    return s;    }


Test


public static void main(String[] args){System.out.println(generate(5));}


0 0