Given an integer
numRows
, return the first numRows of Pascal's triangle.In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
给定一个非负整数
numRows
,生成「杨辉三角」的前numRows
行。在「杨辉三角」中,每个数是它左上方和右上方的数的和。
Example 1:
Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Example 2:
Input: numRows = 1 Output: [[1]]
杨辉三角大家都应该很熟悉,看到这一题大家可能都会有思路,我最初的想法是这样的,最上面一层,我们称为第1层,以此类推,,大家都发现了,第1层的树恒为1,这个时候为了提高效率可以单独拎出来进行判断,第二层也是一样。接下来就是难点,每个数都是他上面左上方和右上方数的和。这个时候我们应该怎么表示呢?
此时层数已经到了第三层,我们发现最左边和最右边的数还是1,此时我们就可以在每次循环的开头和结尾,创建一个List,并且执行add(1)方法。
下面就是核心部分,如何解决每个数是左上方和右上方数的和呢?我们目标层数还有可能不只是一个数,此时还需要考虑再一次的遍历,所以这个时候我们想到了暴力,两个for循环进行遍历。下面来看看代码。
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if (numRows == 0) return res;
res.add(new ArrayList<>(){{add(1);}});
if (numRows == 1) return res;
res.add(new ArrayList<>(){
{
add(1);
add(1);
}
});
if (numRows == 2) return res;
List<Integer> preRow = res.get(1);
for (int i = 3; i <= numRows; i++) {
//首加一
List<Integer> list = new ArrayList<>(){{add(1);}};
for (int j = 1; j < i - 1; j++) {
list.add(preRow.get(j) + preRow.get(j - 1));
}
//尾加一。放置数组下标越界异常
list.add(1);
preRow = list;
res.add(list);
}
return res;
}
}