二刷 07/2022
Version #1 Iteration
Time O(N^2)
Space O(1)
Runtime: 1 ms, faster than 72.34% of Java online submissions for Pascal's Triangle.
Memory Usage: 42.1 MB, less than 29.96% of Java online submissions for Pascal's Triangle.
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>(Arrays.asList(new Integer[]{1})));
for (int i = 1; i < numRows; i++) {
List<Integer> row = new ArrayList<>();
row.add(1);
List<Integer> prevRow = result.get(i - 1);
for (int j = 1; j < prevRow.size(); j++) {
row.add(prevRow.get(j - 1) + prevRow.get(j));
}
row.add(1);
result.add(row);
}
return result;
}
}
一刷
最近特别爱写while,写完了忘了++,结果就死循环。。。19.55 %
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
if (numRows <= 0) return result;
int row = 0;
int col = 0;
List<Integer> curr = null;
List<Integer> prev = null;
while (row < numRows) {
col = 0;
curr = new ArrayList<>();
for (col = 0; col <= row; col++) {
if (col == 0 || col == row) {
curr.add(1);
} else {
prev = result.get(row - 1);
curr.add(prev.get(col - 1) + prev.get(col));
}
}
result.add(curr);
row++;
}
return result;
}
}
No comments:
Post a Comment