119. Pascal‘s Triangle II(Leetcode每日一题-2021.02.12)

Problem

Given an integer rowIndex, return the rowIndexth row of the Pascal’s triangle.

Notice that the row index starts from 0.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Constraints:

  • 0 <= rowIndex <= 33

Example1

Input: rowIndex = 3
Output: [1,3,3,1]

Example2

Input: rowIndex = 0
Output: [1]

Example3

Input: rowIndex = 1
Output: [1,1]

Solution

119. Pascal‘s Triangle II(Leetcode每日一题-2021.02.12)
普通DP到滚动数组

class Solution {
public:
    vector<int> getRow(int n) {
        vector<vector<int>> f(n+1, vector<int>(n + 1));
        for (int i = 0; i <= n; i ++ ) {
            f[i][0] = f[i][i] = 1;
            for (int j = 1; j < i; j ++ )
                f[i][j] = f[i - 1 ][j - 1] + f[i - 1][j];
        }
        return f[n];
    }
};
class Solution {
public:
    vector<int> getRow(int n) {
        vector<vector<int>> f(2, vector<int>(n + 1));
        for (int i = 0; i <= n; i ++ ) {
            f[i & 1][0] = f[i & 1][i] = 1;
            for (int j = 1; j < i; j ++ )
                f[i & 1][j] = f[i - 1  & 1][j - 1] + f[i - 1 & 1][j];
        }
        return f[n & 1];
    }
};
上一篇:for循环输出杨辉三角形(java)


下一篇:Android OpenGLES2.0(四)——正方形和圆形