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

The Idea: Pascal's Triangle can be built off the previous case, so we can iterate to the kth row dynammically. Add 0's to the edges to make things easier and for clean. We can cut these off at the end.

Complexity: O(row_index * (sum i = 1 to row_index (length(root))) time and constant space

vector<int> getRow(int rowIndex) {
    vector<int> root = { 0, 1, 0 };
    for (int row = 1; row <= rowIndex; row++) {
        vector<int> new_root;
        new_root.reserve(root.size() + 2);
        new_root.push_back(0);

        for (int i = 0; i < root.size() - 1; i++) {
            new_root.push_back(root[i] + root[i + 1]);
        }

        new_root.push_back(0);
        root = new_root;
    }

    return vector<int>(root.begin() + 1, root.end() - 1);
}

Last updated