Thursday, September 25, 2014

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

Analysis:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ret(rowIndex+1, 1);
        for(int i=0; i<=rowIndex; i++)
        {
            int last  = 1;
            for(int j=0; j<=i; j++)
            {
                if (j == 0 || j == i)
                    ret[j] = 1;
                else
                {
                    //remember the current value before it is overrided
                    int tmp = ret[j];
                    ret[j] += last;
                    last = tmp;
                }
            }
        }
        
        return ret;
    }
};

No comments:

Post a Comment