Complete the function below. The function receives the number of rows and returns the generated Pascal's Triangle.
Problem: Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows rows of Pascal's Triangle and return them as a 2D array triangle.
Pascal's Triangle is defined as:
Row i (0-indexed) contains i+1 elements.
The first and last element of each row is 1.
For other positions: triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j] for 0 < j < i.
Input
A single integer: numRows
Output
Print a 2D array (you may print each row as a list) representing the first numRows rows.
Constraints
0 ≤ numRows ≤ 30
Example
Input:
5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Example
Input
0
Output
[]
Function Description
Complete solvePascalsTriangle. It has one parameter, int numRows. Return the first numRows rows of Pascal's Triangle as a 2D integer array.
Constraints
Use the limits and requirements stated in the prompt.
解法
逐行构造:第 0 行为 [1],第 i 行除首尾的 1 外,row[j] = prev[j-1] + prev[j]。时间复杂度 O(numRows²),空间复杂度 O(numRows²) 用于结果。
from typing import List
def solvePascalsTriangle(numRows: int) -> List[List[int]]:
res = []
for i in range(numRows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = res[i - 1][j - 1] + res[i - 1][j]
res.append(row)
return resclass Solution {
int[][] solvePascalsTriangle(int numRows) {
int[][] res = new int[numRows][];
for (int i = 0; i < numRows; i++) {
res[i] = new int[i + 1];
res[i][0] = res[i][i] = 1;
for (int j = 1; j < i; j++) {
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
}
return res;
}
}class Solution {
public:
vector<vector<int>> solvePascalsTriangle(int numRows) {
vector<vector<int>> res(numRows);
for (int i = 0; i < numRows; i++) {
res[i].assign(i + 1, 1);
for (int j = 1; j < i; j++) {
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
}
return res;
}
};Given an integer array nums and an integer k, return the k most frequent elements.
To make the output deterministic, sort elements by frequency in descending order. If two elements have the same frequency, the smaller numeric value comes first.
Function Description
Complete solveTopKFrequentElements. It has the following parameters:
int[] nums: the input array
int k: the number of elements to return
Return an int[] containing the top k elements in the deterministic order described above.
Constraints
1 ≤ nums.length ≤ 10⁵ -10⁴ ≤ nums[i] ≤ 10⁴ 1 ≤ k ≤ number of distinct elements in nums
Example 1
Input:
nums = [1,1,1,2,2,3]
k = 2
Output:
[1,2]
Explanation: 1 appears 3 times and 2 appears 2 times, so they are the two most frequent elements.
Example 2
Input:
nums = [4,5,2,1,3]
k = 5
Output:
[1,2,3,4,5]
Explanation: Every number appears once, so ties are resolved by smaller value first.
解锁全部 1 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理