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?

答案

class Solution {
    public List<Integer> getRow(int rowIndex) {
        // Base case, 0 or 1
        if(rowIndex == 0) return Arrays.asList(1);
        if(rowIndex == 1) return Arrays.asList(1, 1);

        int[] list1 = new int[rowIndex+1];
        int[] list2 = new int[rowIndex+1];
        int[] temp = null;
        list1[0] = 1;
        list1[1] = 1;

        for(int i = 2; i <= rowIndex; i++) {
            for(int j = 1; j < i; j++) {
                list2[j] = list1[j - 1] + list1[j];
            }
            list2[0] = 1;
            list2[i] = 1;

            temp = list1;
            list1 = list2;
            list2 = temp;
        }
        List<Integer> ret = new ArrayList<>();
        for (int i = 0; i < list1.length; i++)
            ret.add(list1[i]);

        return ret;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容