[LeetCode] 118. 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
杨辉三角。
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
思路一 - 暴力模拟
按照题意一行一行把元素写出来然后返回整个三角形。
复杂度
时间 O(n^2)
空间 O(n^2)
代码
Java 实现一
1 |
|
思路二 - 固定空间
这个三角形注意一下几点
- 首行只有一个元素 1
- 每一行的第一个和最后一个元素是 1
- 每一行的元素个数 = 行的 index。注意 index 是从 1 开始的
- 中间行位于 index j 的元素 = 上一行位于 j - 1 的元素 + 上一行位于 j 的元素
照着这个思路,我们才能以固定空间复杂度来解决这个问题。这个思路有助于版本二 119 题。
复杂度
时间 O(n^2)
空间 O(k)
代码
Java 实现二 - 固定空间
1 |
|
相关题目
1 |
|
[LeetCode] 118. Pascal's Triangle
https://shurui91.github.io/posts/2757894942.html