array

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3, Return [1,3,3,1].

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> row(rowIndex + 1);

        int prev = 1, cur = 1;
        for(int i = 0; i <= rowIndex; i++){
            //i行
            row[0] = row[i] = 1;
            //i行有i + 1个元素,倒着进行
            for(int j = i - 1; j > 0; j--){
                row[j] = row[j] + row[j - 1];
            }
        }
        return row;
    }
};
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> row(rowIndex + 1);

        int prev = 1, cur = 1;
        for(int i = 0; i <= rowIndex; i++){
            //i行
            row[0] = row[i] = 1;
            //i行有i + 1个元素
            for(int j = 1; j < i; j++){
                cur = row[j];
                row[j] = cur + prev;
                prev = cur;
            }
        }
        return row;
    }
};

results matching ""

    No results matching ""