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

Maximum Product Subarray Problem

LeetCode 152. Given an integer array nums, find a contiguous...

House Robber Problem

LeetCode 198. You are a professional robber planning to rob...

Dungeon Game Problem

LeetCode 174. The demons had captured the princess and imprisoned...

Best Time To Buy And Sell Stock IV Problem

LeetCode 188. You are given an integer array prices where...

Palindrome Partitioning II Problem

LeetCode 132. Given a string s, partition s such that...

Triangle Problem

LeetCode 120. Given a triangle array, return the minimum path...