Pascal's Triangle Problem


Description

LeetCode Problem 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.

Example 1:

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

Example 2:

1
2
Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans(numRows, vector<int>());
        if (numRows == 0)
            return ans;
        ans[0].push_back(1);
        
        for (int i = 1; i < numRows; i ++) {
            ans[i].push_back(1);
            for (int j = 0; j < ans[i-1].size() - 1; j ++) {
                ans[i].push_back(ans[i-1][j] + ans[i-1][j+1]);        
            }
            ans[i].push_back(1);
        }
        
        return ans;
    }
};




Related Posts

Valid Permutations For DI Sequence Problem

LeetCode 903. You are given a string s of length...

Tallest Billboard Problem

LeetCode 956. You are installing a billboard and want it...

Sum Of Subarray Minimums Problem

LeetCode 907. Given an array of integers arr, find the...

Stone Game Problem

LeetCode 877. Alice and Bob play a game with piles...

Split Array With Same Average Problem

LeetCode 805. You are given an integer array nums.

Soup Servings Problem

LeetCode 808. There are two types of soup, type A...