leetcode杨辉三角--只打印一行

mac2026-03-27  5

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

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

示例:

输入: 3 输出: [1,3,3,1] 进阶:

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/pascals-triangle-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 思路 代码

class Solution { public List<Integer> getRow(int rowIndex) { if (rowIndex == 0) { return Arrays.asList(1); } List<Integer> pre = new ArrayList(); List<Integer> temp = null; pre.add(1); for(int i = 1; i <= rowIndex;i++) { temp = new ArrayList(); temp.add(1); for(int j = 1; j < i;j++) { temp.add(pre.get(j)+pre.get(j-1)); } temp.add(1); pre = temp; } return pre; } }
最新回复(0)