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。

1 thought on “LeetCode Pascal’s Triangle

  1. Pingback: LeetCode Pascal’s Triangle II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *