[leetcode] 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?

https://oj.leetcode.com/problems/pascals-triangle-ii/

 

思路:倒序生成即可实现O(k)空间。

 

public class Solution {
    public List<Integer> getRow(int rowIndex) {
        int[] a = new int[rowIndex + 1];

        for (int i = 0; i <= rowIndex; i++) {

            for (int j = rowIndex; j >= 0; j--) {
                if (j == rowIndex || j == 0)
                    a[j] = 1;
                else
                    a[j] = a[j] + a[j - 1];

            }

        }
        List<Integer> res = new ArrayList<Integer>();

        for (int i = 0; i < a.length; i++)
            res.add(a[i]);

        return res;

    }
}

 

第二遍记录:为了方便,用数组做,为了省空间,倒序生成不会覆盖。

public class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<Integer>();
        if(rowIndex<0)
            return res;
        int[] a = new int[rowIndex+1];
        
        for(int i=0;i<=rowIndex;i++){
            for(int j=i;j>=0;j--){
                if(j==0||j==i){
                    a[j]=1;
                }
                else{
                    a[j]=a[j-1]+a[j];
                }
            }
            
        }
        for(int i=0;i<=rowIndex;i++)
            res.add(a[i]);
        
        return res;
    }
}

 

posted @ 2014-07-03 21:06  jdflyfly  阅读(170)  评论(0编辑  收藏  举报