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?

题意:118题的followup,要求只返回第k层,k是从0开始。空间复杂度是否只用O(K)就可以。

思路:按照118的思路,不断的更新上一层pre的信息,最后可以推导出第k层。

public List getRow(int rowIndex) {
    List res = new ArrayList<>();
    if (rowIndex < 0) {
        return res;
    }

    res.add(1);
    List pre = res;
    for (int i = 1; i <= rowIndex; i++) {
        res = new ArrayList<>();
        for (int j = 0; j <= i; j++) {
            if (j == 0 || j == i) {
                res.add(1);
            } else {
                res.add(pre.get(j - 1) + pre.get(j));
            }
        }
        pre = res;
    }

    return res;
}

但是根据每个上层来推导下层,空间复杂度将无法满足O(K)的要求,查看discuss答案,发现它的思路是从后往前不断的拓宽当前层。

public List getRow(int rowIndex) {
    List list = new ArrayList();
    if (rowIndex < 0)
        return list;

    for (int i = 0; i < rowIndex + 1; i++) {
        list.add(0, 1);
        for (int j = 1; j < list.size() - 1; j++) {
            list.set(j, list.get(j) + list.get(j + 1));
        }
    }
    return list;
}

你可能感兴趣的:(Leetcode 119. Pascal's Triangle II)