LeetCode每日一题:帕斯卡三角(杨辉三角) 2

问题描述

Given an index k, return the k th 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?

问题分析

这题是打印某一层的值,直接改动一下上一题的返回值即可。
这样虽然能够AC,但是不符合只使用O(k)的额外空间,正确的做法是用一个queue记录上一层的值,不断地更新,才能不使用额外空间。

代码实现

public ArrayList getRow(int rowIndex) {
        ArrayList> list = new ArrayList>();
        for (int i = 0; i <= rowIndex; i++) {
            ArrayList curList = new ArrayList<>();
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i) curList.add(1);
                else curList.add(list.get(i - 1).get(j - 1) + list.get(i - 1).get(j));
            }
            list.add(curList);
        }
        return list.get(rowIndex);
    }

你可能感兴趣的:(LeetCode每日一题:帕斯卡三角(杨辉三角) 2)