Tag Archives: 杨辉三角

LeetCode Pascal’s Triangle II

119. Pascal’s Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Note that the row index starts from 0.


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

Example:

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

Follow up:

Could you optimize your algorithm to use only O(k) extra space?


本题在LeetCode Pascal’s Triangle的基础上,要求只用O(k)空间复杂度,输出杨辉三角的第k行结果。
关键在于只能用O(k)的空间。我们要算第k行的结果,只要知道第k-1行结果就可以了,所以可以用O(k)的空间保留前一行的结果。每计算到一行就交换一下ans和tmp,完整代码如下:

class Solution {
public:
    vector<int> getRow(int rowIndex)
    {
        vector<int> ans(rowIndex + 1, 1), tmp(rowIndex + 1, 1);
        if (rowIndex == 0 || rowIndex == 1)
            return ans;
        for (int row = 2; row <= rowIndex; row++) {
            for (int col = 1; col < row; col++) {
                tmp[col] = ans[col – 1] + ans[col];
            }
            swap(ans, tmp);
        }
        return ans;
    }
};

本代码提交AC,用时0MS。

其实这题不需要tmp数组也行,就是每行算的时候从后往前算,因为ans[col]只会用到ans[col]和ans[col-1],所以从后往前填数组,即使覆盖了之前的结果,也对前面的计算没有影响。
这种思路在DP解背包问题中很常见,完整代码如下:

class Solution {
public:
    vector<int> getRow(int rowIndex)
    {
        vector<int> ans(rowIndex + 1, 1);
        if (rowIndex == 0 || rowIndex == 1)
            return ans;
        for (int row = 2; row <= rowIndex; row++) {
            for (int col = row – 1; col > 0; col–) {
                ans[col] += ans[col – 1];
            }
        }
        return ans;
    }
};

本代码提交AC,用时0MS。

LeetCode Pascal’s Triangle

118. Pascal’s Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.


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

Example:

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

本题要求生成前n行的Pascal’s Triangle,其实这东西就是中国的杨辉三角。下一行的第j个元素等于上一行的第j-1、j个元素之和。根据这个规律很容易写出代码,如下:

class Solution {
public:
    vector<vector<int> > generate(int numRows)
    {
        vector<vector<int> > ans;
        if (numRows == 0)
            return ans;
        ans.push_back({ 1 });
        for (int i = 2; i <= numRows; i++) {
            vector<int> cur = { 1 };
            for (int j = 1; j <= i – 2; j++) {
                cur.push_back(ans[i – 2][j – 1] + ans[i – 2][j]);
            }
            cur.push_back(1);
            ans.push_back(cur);
        }
        return ans;
    }
};

本代码提交AC,用时0MS。