Saturday, April 11, 2015

Pascal Triangle 2

Problem:


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?
Solution:
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> helper_prev, helper_curr;
        
        // Base case.
        helper_prev.push_back(1);
        
        for (int i = 0; i < rowIndex; i++) {
            helper_curr.push_back(1);
            int size = helper_prev.size();
            for (int prev_iter = 0; prev_iter < (size - 1); prev_iter++) {
                helper_curr.push_back(helper_prev[prev_iter] + helper_prev[prev_iter+1]);
            }
            helper_curr.push_back(1);
            helper_prev = helper_curr;
            // make helper_curr blank
            helper_curr.clear();
        }
        return helper_prev;
    }
};

No comments:

Post a Comment