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 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 ret = new ArrayList<>();
        for (int i = 0; i < list1.length; i++)
            ret.add(list1[i]);

        return ret;
    }
}

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