玩命加载中 . . .

118-杨辉三角


LeetCode 118. Pascal’s Triangle

LeetCode-118

Given an integer numRows, return the first numRows of Pascal’s triangle.

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

Example 1:

Input: numRows = 5
Output: 
[
 [1],
 [1,1],
 [1,2,1],
 [1,3,3,1],
 [1,4,6,4,1]
]

method

状态转换方程:dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
使用滚动数组,每次i循环都在dp后面插入一个1,第一个1和最后一个1不用处理
只要处理dp中间部分就可以了,注意要从后往前

vector<vector<int>> generate(int numRows) {
    vector<vector<int>> res;
    vector<int> dp;
    for (int i = 0; i < numRows; i++) {
        dp.push_back(1);
        for (int j = i - 1; j > 0; j--) {   // 从后往前处理
            dp[j] += dp[j - 1];
        }
        res.push_back(dp);
    }
    return res;
}

LeetCode 119. Pascal’s Triangle II

LeetCode-119

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle.

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

Example 1:

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

method

vector<int> getRow(int rowIndex) {
    vector<int> dp;
    for (int i = 0; i <= rowIndex; i++) {
        dp.push_back(1);
        for (int j = i - 1; j > 0; j--) {
            dp[j] += dp[j - 1];
        }
    }
    return dp;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录