您的位置:首页 > 其它

Leetcode Pascal's Triangle

2015-10-06 02:47 381 查看
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]
]


解题思路:

用上一次生成的array 生成新的array.

Java code:

public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0; i < numRows; i++) {
List<Integer> arr = new ArrayList<Integer>();
if(result.size() == 0) {
arr.add(1);
}else {
List<Integer> old = result.get(result.size()-1);
arr.add(1);
for(int j = 0; j < old.size()-1; j++) {
arr.add(old.get(j) + old.get(j+1));
}
arr.add(1);
}
result.add(arr);
}
return result;
}


Reference:

1. http://www.programcreek.com/2014/03/leetcode-pascals-triangle-java/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: