[LeetCode] 119. Pascal's Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

杨辉三角 II。

跟版本一类似,也是计算杨辉三角,但是只需要输出某一行的结果即可,规定只允许使用 O(n) 级别的额外空间。

参考版本一的思路二,重复利用 list 数组即可。版本一的思路是当前 index = j 上的数字是之前一行的 j 和 j - 1 的和。但是这道题的 followup 是只能使用固定的额外空间,按照版本一的做法是会覆盖之前的结果的。所以对于每一行,我们从右往左开始算,这样就不会覆盖之前的结果了。记得最后加上每一行的最后一个 1。

时间O(n^2)

空间O(n)

Java实现

 1 class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         List<Integer> res = new ArrayList<>();
 4         res.add(1);
 5         for (int i = 1; i <= rowIndex; i++) {
 6             for (int j = res.size() - 1; j > 0; j--) {
 7                 res.set(j, res.get(j - 1) + res.get(j));
 8             }
 9             res.add(1);
10         }
11         return res;
12     }
13 }

 

这里还有一种思路,是从左往右算。我们可以把题目给的例子三角形转化一下,如果我们试着把他看做一个直角三角形,那么数字的排列会是如下。

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 相同的数字计算而来。

i = 0
[1]
[1]
i = 1
[1, 1]
[1, 1]
i = 2
[1, 1, 1]
[1, 2, 1]
i = 3
[1, 1, 2, 1]
[1, 3, 3, 1]
i = 4
[1, 1, 3, 3, 1]
[1, 4, 6, 4, 1]
i = 5
[1, 1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

时间O(n^2)

空间O(n)

Java实现

 1 class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         List<Integer> list = new ArrayList<>();
 4         for (int i = 0; i <= rowIndex; i++) {
 5             // first 1 at each row
 6             list.add(0, 1);
 7             for (int j = 1; j < list.size() - 1; j++) {
 8                 list.set(j, list.get(j) + list.get(j + 1));
 9             }
10         }
11         return list;
12     }
13 }

 

相关题目

118. Pascal's Triangle

119. Pascal's Triangle II

120. Triangle

799. Champagne Tower

2221. Find Triangular Sum of an Array

LeetCode 题目总结

posted @ 2020-05-14 08:10  CNoodle  阅读(432)  评论(0编辑  收藏  举报