您的位置:首页 > 其它

Leetcode 118. Pascal's Triangle

2018-03-14 10:59 423 查看

题目

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


解法一

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
if (numRows == 0)
return list;
List<Integer> tmp = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
tmp.add(0, 1);
for (int j = 1; j < tmp.size() - 1; j++) {
tmp.set(j, tmp.get(j) + tmp.get(j + 1));
}
list.add(new ArrayList<>(tmp));
}
return list;
}
}


解法二

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
if (numRows == 0)
return list;
int[][] result = new int[numRows][];
int[] tmp = new int[1];
tmp[0] = 1;
result[0] = tmp;
for (int i = 0; i < numRows; i++) {
tmp = new int[i + 1];
tmp[0] = 1;
tmp[tmp.length - 1] = 1;
for (int j = 1; j < tmp.length - 1; j++) {
tmp[j] = result[i-1][j - 1] +result[i-1][j];
}
result[i] = tmp;
}
return (List)Arrays.asList(result);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: