【每日刷题】杨辉三角
118. 杨辉三角 - 力扣(LeetCode)
话先放在前面,无论数学好不好,都能写,不用自己推导。
记录一下我自己的AC代码。首先初始化第一行,放入res。之后继续生成每一行,首尾都是1,其余每个数字等于上一行的左右两个数字之和,然后把新的一行放入res,用cur记录新的一行。
class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> res = new ArrayList<>();int pos = 1;List<Integer> cur = new ArrayList<>();cur.add(1);res.add(cur);while(pos < numRows) {List nxt = new ArrayList<>();nxt.add(1);for(int i = 0; i < cur.size() - 1; i++) {int num = cur.get(i) + cur.get(i+1);nxt.add(num);}nxt.add(1);res.add(nxt);cur = nxt;pos++;}return res;}
}
下面是根据官方题解修改的版本,更简洁一些。差别如下:
- 把while循环改成了for循环,因为反正每次都要自增。
- 不用cur来额外记录上一行,直接用 res.get(i-1) 取得上一行即可。
- 首尾设置为1用 if(j == 0 || j == i) 判断,更结构化一些。
class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> res = new ArrayList<>();for(int i = 0; i < numRows; i++) {List cur = new ArrayList<>();for(int j = 0; j <= i; j++) {if(j == 0 || j == i) {cur.add(1);} else {int num = res.get(i - 1).get(j - 1) + res.get(i - 1).get(j);cur.add(num);}}res.add(cur);}return res;}
}