[LeetCode] 119. Pascal's Triangle II
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
Example 3:
Input: rowIndex = 1
Output: [1,1]
Constraints:
0 <= rowIndex <= 33
Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?
杨辉三角 II。
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。在「杨辉三角」中,每个数是它左上方和右上方的数的和。
思路
跟版本一类似,也是计算杨辉三角,但是只需要输出某一行的结果即可,规定只允许使用 O(n) 级别的额外空间。
参考版本一的思路二,重复利用 list 数组即可。版本一的思路是当前 index = j 上的数字是之前一行的 j 和 j - 1 的和。但是这道题的 followup 是只能使用固定的额外空间,按照版本一的做法是会覆盖之前的结果的。所以对于每一行,我们从右往左开始算,这样就不会覆盖之前的结果了。记得最后加上每一行的最后一个 1。
思路一
参考版本一的思路二,重复利用 list 数组即可。版本一的思路是当前 index = j 上的数字是之前一行的 j 和 j - 1 的和。但是这道题的 followup 是只能使用固定的额外空间,按照版本一的做法是会覆盖之前的结果的。所以对于每一行,我们从右往左开始算,这样就不会覆盖之前的结果了。记得最后加上每一行的最后一个 1。
复杂度
时间O(n^2)
空间O(n)
代码
Java实现
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>();
res.add(1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = res.size() - 1; j > 0; j--) {
res.set(j, res.get(j - 1) + res.get(j));
}
res.add(1);
}
return res;
}
}
思路二
这里还有一种思路,是从左往右算。我们可以把题目给的例子三角形转化一下,如果我们试着把他看做一个直角三角形,那么数字的排列会是如下。
1
11
121
1331
14641
注意到除了头两行情况比较特殊,只有 1 组成,从第三行开始,中间某个位置 i 上的数字 = 上一行同位置 i 上的数字 + 上一行 i - 1 位置上的数字。我在代码中的几个地方做了 print,参见 print 的结果。处理当前行的时候,我们先在 list 的头部加一个 1,然后对于 index j 上的数字,我们把它修改为 (index j) + (index j + 1)。注意 j 的 for 循环要小于 i,因为第 i 行只能有 i 个元素。从第三行开始,所有非零的数字都是通过上一行 index 相同的数字计算而来。
复杂度
时间O(n^2)
空间O(n)
代码
Java实现
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i <= rowIndex; i++) {
// first 1 at each row
list.add(0, 1);
for (int j = 1; j < list.size() - 1; j++) {
list.set(j, list.get(j) + list.get(j + 1));
}
}
return list;
}
}
相关题目
118. Pascal's Triangle
119. Pascal's Triangle II
120. Triangle
799. Champagne Tower
2221. Find Triangular Sum of an Array