1. 题目描述
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
2. 示例
3. 思路
- 每行开始结束都是1。
- 每行中间(除开始值和结束值外)都是上一行相同位置以及相同位置前一位值的相加。
4. 遇上的问题
无。。
5. 具体实现代码
自己写的代码
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> numRowLists = new ArrayList<List<Integer>>();
List<Integer> numRowList = new ArrayList<Integer>();
List<Integer> numRowListTemp = new ArrayList<Integer>();
if (numRows == 0){
return numRowLists;
}
numRowList.add(1);
numRowLists.add(numRowList);
for (int i = 2;i <= numRows;i++){
numRowListTemp = numRowList;
numRowList = new ArrayList<Integer>();
for(int j = 1;j <= i; j++){
if ( j == 1 || j == i ){
numRowList.add(1);
continue;
}
numRowList.add(numRowListTemp.get(j-2)+numRowListTemp.get(j-1));
}
numRowLists.add(numRowList);
}
return numRowLists;
}
}
6. 学习收获,官方一如既往的妙啊
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; ++i) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i) {
row.add(1);
} else {
row.add(ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j));
}
}
ret.add(row);
}
return ret;
}
}
代码来源
区别在于我多了一个值的复制过程,我原来以为我的做法会损空间获得更多的时间。
7 题目来源
做题主要是静心,很快就可以出结果。------swrici