0%

LeetCode-118

题目

Snipaste_2020-12-06_10-53-12.png

结果

Snipaste_2020-12-06_10-52-13.png

代码

七个月前的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new LinkedList<>();
if (numRows == 0) {
return ans;
}
ans.add(List.of(1));
if (numRows == 1) {
return ans;
}
ans.add(List.of(1, 1));
for (int i = 2; i < numRows; i++) {
List<Integer> list = new LinkedList<>();
list.add(1);
for (int j = 0; j + 1 < ans.get(i - 1).size(); j++) {
list.add(ans.get(i - 1).get(j) + ans.get(i - 1).get(j + 1));
}
list.add(1);
ans.add(list);
}
return ans;
}
}

七个月后的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> row = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
row.add(1);
} else {
row.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));
}
}
ans.add(row);
}
return ans;
}
}

复杂度

时间复杂度:O(n²)

空间复杂度:O(1)