Pascal Triangle

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?

10/31

這道題挺簡單的, 還是犯了兩個小錯,見err1 和 err2

    public List<Integer> getRow(int n) {
        // err1: ask if n could be 0?
        List<Integer> row = new ArrayList<Integer>();
        row.add(1);
        for(int i=0; i<n; i++){
            List<Integer> copy = new ArrayList<Integer>(row);
            row = new ArrayList<Integer>();
            row.add(1);
            int len = copy.size();
            for(int j=0; j<len-1; j++){ //err2: use a different index other than j
                row.add(copy.get(j) + copy.get(j+1));
            }
            row.add(1);
        }
        // directly return [1] on n=0
        
        return row;
    }
}
時間複雜度:

一共有n個循環, 在第i個循環生成第i行, 大約要做i個加法, 所以複雜度大概是O(n^2)

空間複雜度:

在每個循環中需要先儲存上一個循環中得到的結果, 加上每次都需要記錄目前的結果, 所以複雜度是O(n)\


Follow up: Further improvement:

Without extra space to store the previous  row, we can scan each row backwards

public class Solution {
    public List<Integer> getRow(int n) {
        // err1: ask if n could be 0?
        List<Integer> row = new ArrayList<Integer>();
        row.add(1);
        for(int i=0; i<n; i++){
            int len = row.size();
            for(int j=len-1; j>0; j--){
                row.set(j, row.get(j) + row.get(j-1));
            }
            
            row.add(1); // err1 : only need to append to the end; the first element is always 1: never reset
        }
        // directly return [1] on n=0
        
        return row;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章