LeetCode13-罗马数字转整数

题目链接

英文链接:https://leetcode.com/problems/pascals-triangle-ii/

中文链接:https://leetcode-cn.com/problems/pascals-triangle-ii/

题目详述

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

1
2
输入: 3
输出: [1,3,3,1]

进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

题目详解

  • LeetCode118-杨辉三角 是求前 k 行,而本题是求第 k 行(下标从 0 开始)。
  • 可以直接初始化第 k 行的空间,为了避免覆盖上一行的值,采用逆序更新的方法迭代结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class LeetCode_00119 {

public List<Integer> getRow(int rowIndex) {
List<Integer> res = new ArrayList<>(rowIndex + 1);
res.add(1);
for (int i = 1; i <= rowIndex; ++i) {
for (int j = i - 1; j > 0; --j) {
res.set(j, res.get(j) + res.get(j - 1));
}
res.add(1);
}
return res;
}
}