118. Pascal’s Triangle
https://leetcode.com/problems/pascals-triangle-ii/
Description
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?
Solutions
上一道要求输出整个Pascal’s Triangle,这道要求输出指定的那一行。
Pascal’s Triangle中因为是求出全部结果,所以我们需要上一行的数据就很自然的可以去取。而这里我们只需要一行数据,就得考虑一下是不是能只用一行的空间来存储结果而不需要额外上一行呢?
对于每一行我们知道如果从前往后扫,第i个元素的值等于上一行的res[i]+res[i+1],可以看到数据是往前看的,如果我们只用一行空间,那么需要的数据就会被覆盖掉。
所以这里采取的方法是从后往前扫,这样每次需要的数据就是res[i]+res[i-1],我们需要的数据不会被覆盖,因为需要的res[i]只在当前步用,下一步就不需要了。
这个技巧在动态规划省空间时也经常使用,主要就是看我们需要的数据是原来的数据还是新的数据来决定我们遍历的方向。时间复杂度还是O(n^2),而空间这里是O(k)来存储结果,仍然不需要额外空间。
这道题相比于Pascal’s Triangle其实更有意思一些,因为有一个考点就是能否省去额外空间,在面试中出现的可能性大一些,不过总体比较简单,电面中比较合适。
Submissions
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if (rowIndex < 0)
return list;
for (int i = 0; i < rowIndex + 1; i++) {
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;
}
}
Summary
从前往后扫和从后往前扫。
REF:
https://www.cnblogs.com/ccsccs/articles/4214260.html