Friday, September 8, 2017

119. Pascal's Triangle II

https://leetcode.com/problems/pascals-triangle-ii/description/
Solution 1. Iteration
rowIndex        row
i = 0           1 0 0 0 0
i = 1           1 1 0 0 0
i = 2           1 2 1 0 0
i = 3           1 3 3 1 0
i represents the ith row of the pascals triangle
j is the index on ith row, index loops from high to low
    vector<int> getRow(int rowIndex) {
        vector<int> r(rowIndex+1, 0);
        r[0] = 1;
        for(int i=1; i<rowIndex+1; i++) {
            for(int j=i; j>=1; j--)
                r[j] += r[j-1];
        }
        return r;

    }
Solution 2. recursion
    vector<int> getRow(int rowIndex) {
        if(rowIndex == 0) return {1};
        vector<int> r = getRow(rowIndex - 1);
        r.push_back(1);
        for(int i=1, n, m=r[0]; i<r.size()-1; i++) {
            n = r[i];
            r[i] = m + r[i];
            m = n;
        }
        return r;
    }

No comments:

Post a Comment