118. Pascal’s Triangle LeetCode Solution
In this guide, you will get 118. Pascal’s Triangle LeetCode Solution with the best time and space complexity. The solution to Pascal’s Triangle problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Pascal’s Triangle solution in C++
- Pascal’s Triangle solution in Java
- Pascal’s Triangle solution in Python
- Additional Resources
Problem Statement of Pascal’s Triangle
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]]
Example 2:
Input: numRows = 1
Output: [[1]]
Constraints:
1 <= numRows <= 30
Complexity Analysis
- Time Complexity: O(n^2)
- Space Complexity: O(n^2)
118. Pascal’s Triangle LeetCode Solution in C++
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans;
for (int i = 0; i < numRows; ++i)
ans.push_back(vector<int>(i + 1, 1));
for (int i = 2; i < numRows; ++i)
for (int j = 1; j < ans[i].size() - 1; ++j)
ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];
return ans;
}
};
/* code provided by PROGIEZ */
118. Pascal’s Triangle LeetCode Solution in Java
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ans = new ArrayList<>();
for (int i = 0; i < numRows; ++i) {
Integer[] temp = new Integer[i + 1];
Arrays.fill(temp, 1);
ans.add(Arrays.asList(temp));
}
for (int i = 2; i < numRows; ++i)
for (int j = 1; j < ans.get(i).size() - 1; ++j)
ans.get(i).set(j, ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));
return ans;
}
}
// code provided by PROGIEZ
118. Pascal’s Triangle LeetCode Solution in Python
class Solution:
def generate(self, numRows: int) -> list[list[int]]:
ans = []
for i in range(numRows):
ans.append([1] * (i + 1))
for i in range(2, numRows):
for j in range(1, len(ans[i]) - 1):
ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.