LeetCode|Pascal's Triangle II-java

来源:互联网 发布:北方金银分析软件 编辑:程序博客网 时间:2024/06/04 18:48

题目:

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?

思路:

给定一个数n,输出杨辉三角第n行数的数据,并且要求空间复杂度为o(k),和之前返回所有的杨辉三角类似,先将第n-1行写入内存中,当在第n行时,需要从后往前赋值,这样不会将未使用到的数字覆盖。

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



0 0