您的位置:首页 > 其它

LeetCode-118-Pascal's Triangle(帕斯卡的三角形)

2017-08-19 09:53 489 查看
Q:

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


Analysis:

基础的算法问题,中间元素值等于“肩上”两元素之和。

Code:

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> out = new ArrayList<List<Integer>>();
if (numRows == 0) {
return out;
} else {
for (int i = 1; i <= numRows; i++) {
ArrayList<Integer> in = new ArrayList<Integer>();
for (int j = 0; j < i; j++) {
if (j == 0 || j == i - 1) {
in.add(1);
} else {
in.add(out.get(i - 2).get(j - 1) + out.get(i - 2).get(j));
}
}
out.add(in);
}
}
return out;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: