杨辉三角
/**
* 自己的代码,感觉区分的特殊情况太多了,应该有更简洁的
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 37 MB, less than 48.58%
*/
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList();
List<Integer> first = new ArrayList<Integer>();
first.add(1);
res.add(first);
for (int i = 2; i <= numRows; i++) {
List<Integer> currList = new ArrayList<Integer>();
currList.add(1);
for (int j = 1; j < i - 1; j++) {
currList.add(res.get(i - 2).get(j - 1) + res.get(i - 2).get(j));
}
currList.add(1);
res.add(currList);
}
return res;
}
}
/**
* 把第一行、每一行首尾这样的特殊情况都写在内层循环里,简洁一点但会在循环中增加判断
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.9 MB, less than 65.75%
*/
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList();
for (int i = 0; i < numRows; i++) {
List<Integer> currL = new ArrayList();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
currL.add(1);
} else {
currL.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j));
}
}
res.add(currL);
}
return res;
}
}
/**
* 讨论区的做法,用一个ArrayList不断更新为每一行,每行计算完将其当前状态新建为一个list添加到res
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.6 MB, less than 95.08%
*/
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList();
List<Integer> row = new ArrayList();
for (int i = 0; i < numRows; i++) {
row.add(0, 1); // add 1 in the head, make both the first element and the amount of elements in the new row right
for (int j = 1; j < row.size() - 1; j++) { // don't have to set the last element, which would always be 1
row.set(j, row.get(j) + row.get(j + 1));
}
res.add(new ArrayList(row));
}
return res;
}
}