您的位置:首页 > 编程语言 > Java开发

Pascal's Triangle (Java)

2014-12-23 17:05 260 查看
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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode