给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 *k *行。
image.png
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
方法二:空间复杂度 O(k)O(k)
题目中给了一个进阶问题,能不能用 O(k)O(k) 的空间复杂度呢?
其实是可以的,我们只用一个长度为 kk 的一维数组。类似于动态规划中滚动数组的思路。
使用一维数组,然后从右向左遍历每个位置,每个位置的元素res[j]res[j] += 其左边的元素 res[j - 1]res[j−1]。
为啥不从左向右遍历呢?因为如果从左向右遍历,那么左边的元素已经更新为第 i 行的元素了,而右边的元素需要的是第 i - 1i−1 行的元素。故从左向右遍历会破坏元素的状态。
https://pic.leetcode-cn.com/1613104362-xmiBfu-119_2.gif
public class Solution {
public IList<int> GetRow(int rowIndex) {
IList<int> res = new List<int>();
res.Add(1);
for(int i = 1; i <= rowIndex; i++){
res.Add(0);
for(int j = i; j > 0 ; j--){
res[j] = res[j - 1] + res[j];
}
}
return res;
}
}
public class Solution {
public IList<int> GetRow(int rowIndex) {
if(rowIndex == 0) {
IList<int> first = new List<int>();
first.Add(1);
return first;
}
IList<int> pre = GetRow(rowIndex - 1);
IList<int> newList = new List<int>(pre.Count + 1);
for(int i = 0; i < pre.Count + 1; i++){
if(i == 0 || i == pre.Count) newList.Add(1);
else newList.Add(pre[i-1] + pre[i]);
}
return newList;
}
}