119. 杨辉三角 II - 力扣(LeetCode) (leetcode-cn.com)
难度:简单
题目描述:给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
Java刷题随笔—118. 杨辉三角
杨辉三角性质
- 每行数字左右对称,由 1 开始逐渐变大再变小,并最终回到 1。
- 第 n 行(从 0 开始编号)的数字有 n+1 项,前 n 行共有 n ( n + 1 ) 2 \frac{n(n+1)}{2} 2n(n+1) 个数。
- 第 n 行的第 m 个数(从 0 开始编号)可表示为可以被表示为组合数 C ( n , m ) \mathcal{C}(n,m) C(n,m) ,记作 C n m \mathcal{C}_n^m Cnm 或 ( n m ) \binom{n}{m} (mn) ,即为从 n 个不同元素中取 m 个元素的组合数。我们可以用公式来表示它: C n m = n ! m ! ( n − m ) ! \mathcal{C}_n^m=\dfrac{n!}{m!(n-m)!} Cnm=m!(n−m)!n!
- 每个数字等于上一行的左右两个数字之和,可用此性质写出整个杨辉三角。即第 n 行的第 i 个数等于第 n−1 行的第 i−1 个数和第 i 个数之和。这也是组合数的性质之一,即 C n i = C n − 1 i + C n − 1 i − 1 \mathcal{C}_n^i=\mathcal{C}_{n-1}^i + \mathcal{C}_{n-1}^{i-1} Cni=Cn−1i+Cn−1i−1
- ( a + b ) n (a+b)^n (a+b)n 的展开式(二项式展开)中的各项系数依次对应杨辉三角的第 n 行中的每一项。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/yang-hui-san-jiao-ii-by-leetcode-solutio-shuk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
分析1
此题和118杨辉三角一致,可以通过118题生成杨辉三角的角度进行解题。
通过118题思路,对此题可以有三种解法。
1- 根据118生成杨辉三角,并按 rowIndex 返回对应行。 时间复杂度:O(rowIndex*rowIndex),空间复杂度:O(rowIndex*rowIndex)
2- 对1进行优化,由于1中需要保存整个杨辉三角,但是并不需保存整个杨辉三角,所以使用一个数组只保存上一行数据。 时间复杂度:O(rowIndex*rowIndex),空间复杂度:O(rowIndex)
3- 对2进行优化,2中使用了两个数组用于保存数组,一个是当前行数组,一个是前一行数组。所以我们可以根据前一行数组上进行更改,并从后遍历。 时间复杂度:O(rowIndex*rowIndex),空间复杂度:O(1)
解题1
1:
class Solution {
public List<Integer> getRow(int rowIndex) {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
List<Integer> currentList = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (i == j || j == 0) {
currentList.add(1);
} else {
currentList.add(result.get(i - 1).get(j - 1) + result.get(i - 1).get(j));
}
}
result.add(currentList);
}
return result.get(rowIndex);
}
}
2:
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> before = new ArrayList<>();
for (int i = 0; i <= rowIndex; i++) {
List<Integer> current = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j==0 || j==i){
current.add(1);
} else {
current.add(before.get(j-1) + before.get(j));
}
}
before = current;
}
return before;
}
}
3:
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> before = new ArrayList<>();
before.add(1);
for (int i = 1; i <= rowIndex; i++) {
before.add(0);
for (int j = i; j > 0; j--) {
before.set(j, before.get(j) + before.get(j - 1));
}
}
return before;
}
}
分析2
根据杨辉三角性质3:进行直接计算。 时间复杂度:O(rowIndex),空间复杂度:O(1)
解题2
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> before = new ArrayList<>();
before.add(1);
for (int i = 1; i <= rowIndex; i++) {
before.add((int) ((long) before.get(i - 1) * (rowIndex - i + 1) / i));
}
return before;
}
}