LeetCode——杨辉三角 i-ii

Q:给出一个值numRows,生成杨辉三角的前numRows行
例如,给出 numRows = 5,
返回
[↵ [1],↵ [1,1],↵ [1,2,1],↵ [1,3,3,1],↵ [1,4,6,4,1]↵]
A:

    public static ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
        if (numRows == 0)
            return arrayLists;
        ArrayList<Integer> array = new ArrayList<>();
        for (int i = 1; i <= numRows; i++) {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (int j = 0; j < i; j++) {
                if (j == 0 || j == i - 1)
                    arrayList.add(1);
                else
                    arrayList.add(array.get(j - 1) + array.get(j));
            }
            array = arrayList;
            arrayLists.add(arrayList);
        }
        return arrayLists;
    }

Q:给出一个索引k,返回杨辉三角的第k行
例如,k=3,
返回[1,3,3,1].
备注:
你能将你的算法优化到只使用O(k)的额外空间吗?
A:
注意,行数是从0开始的。使用从后往前计算。

    public static ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> array = new ArrayList<>();
        for (int i = 0; i <= rowIndex; i++) {
            for (int j = i - 1; j > 0; j--) {
                array.set(j, array.get(j) + array.get(j - 1));
            }
            array.add(1);
        }
        return array;
    }
posted @ 2020-03-15 21:53  Shaw_喆宇  阅读(130)  评论(0编辑  收藏  举报