Pacal'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:
    vector<int> getRow(int rowIndex) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> row;
        if (0 == rowIndex){
            row.push_back(1);
            return row;
        }
        
        row = getRow(rowIndex -1);
        
        vector<int> new_row;
        new_row.push_back(1);
        for(size_t i = 0; i + 1 < row.size(); i++){
            new_row.push_back(row[i] + row[i+1]);
        }
        
        new_row.push_back(1);
        
        return new_row;
    }
};

Above the space complexity is O(k^2) because in recursion, vector <row> is used, which means 1+2+3+4...+k = k(k+1)/2 = O(k^2)

We can optimize it by down-to-up,so just reserve the k-1'th vector for k and the space and reused.

posted @ 2013-02-13 19:49  一只会思考的猪  阅读(135)  评论(0编辑  收藏  举报