LeetCode 119 Pascal's Triangle II

题目描述

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,
Return [1,3,3,1].

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

分析

只利用一个数组,自上而下计算并存储第k行的值。

如k=7,则数组的值分别为:

[1, 2, 1, 1, 1, 1, 1, 1]
[1, 3, 3, 1, 1, 1, 1, 1]
[1, 4, 6, 4, 1, 1, 1, 1]
[1, 5, 10, 10, 5, 1, 1, 1]
[1, 6, 15, 20, 15, 6, 1, 1]
[1, 7, 21, 35, 35, 21, 7, 1]

代码

    public List<Integer> getRow(int rowIndex) {

        Integer[] row = new Integer[rowIndex + 1];
        Arrays.fill(row, 1);

        for (int i = 0; i < rowIndex - 1; i++) {
            for (int j = i + 1; j >= 1; j--) {
                row[j] = row[j] + row[j - 1];
            }
        }

        return Arrays.asList(row);
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50107839
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞