LeetCode-Pascal's Triangle II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82529533

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?

题意:要求返回指定行的杨辉三角;并且其空间复杂度为O(k);

解法:我们知道在杨辉三角中,下一行需要使用到上一行的数据;因此,我们可以先将上一行的结果保留,用于计算下一行,等到下一行数据计算完毕后,再删除上一行的数据,重复这个操作,知道得到指定行的数据;
例如:我们现在已经留有第三行的结果list=[1,2,1],这个时候我们根据第三行的结果来计算第四行得到list=[1,2,1,1,3,3,1],随后我们再删除前一行的数据得到list=[1,3,3,1];

Java
class Solution {
    public List<Integer> getRow(int rowIndex) {
        LinkedList<Integer> result = new LinkedList<>();
        result.addLast(1);
        for (int i = 1; i <= rowIndex; i++) {
            result.addLast(1);
            for (int j = 0; j <= i - 2; j++) {
                result.addLast(result.get(j) + result.get(j + 1));
            }
            result.addLast(1);
            while (result.size() > i + 1) {
                result.removeFirst();
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82529533