119. 杨辉三角 II(java)

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 3
输出: [1,3,3,1]代码一:
class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> list = new ArrayList<>();
        if (rowIndex < 0)
            return list;
        list.add(1);
        if (rowIndex == 0)
            return list;
        for (int i = 1; i <= rowIndex ; i++) {
            for (int j = list.size()-1; j > 0; j--) {
                list.set(j,list.get(j-1)+list.get(j));
            }
            list.add(1);
        }
        return list;

    }
}

进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

思路:

在O(k)的空间复杂度的限制下,在长度为k的数组内部,从杨辉三角的第一行开始依次计算到第k行的最终结果。

代码中i的值是第k行,j是第j个数。j从i开始,是因为第i行共有i+1个数字,从后往前计算,避免了第i-1行计算结果被覆盖丢失。

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

每一个数组都比上一个数组多一个数,第一位和最后一位都是1, 其余数字都是上一个数组对应位置和前一位置的数字的和 a[i][j] = a[i-1][j] + a[i-1][j-1]


class Solution {
    public List<Integer> getRow(int rowIndex) {
        Integer[] result = new Integer[rowIndex+1];//new一个集合类对象,数组中有rowIndex个元素
        Arrays.fill(result, 0);//填充0
        result[0] = 1;
        for(int i = 1; i<result.length; i++) {
            for(int j=i;j>0;j--) {
                result[j] = result[j] + result[j-1];
            }
        }
        return Arrays.asList(result);//返回一个受指定数组支持的固定大小的列表(result)
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40449300/article/details/84405020
今日推荐