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;
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容