119. 杨辉三角 II
给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: rowIndex = 3 输出: [1,3,3,1]
示例 2:
输入: rowIndex = 0 输出: [1]
示例 3:
输入: rowIndex = 1 输出: [1,1]
提示:
0 <= rowIndex <= 33
进阶:
你可以优化你的算法到 O(rowIndex)
空间复杂度吗?
相似题目
原站题解
java 解法, 执行用时: 0 ms, 内存消耗: 39.4 MB, 提交时间: 2023-11-28 10:18:58
class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> row = new ArrayList<Integer>(); row.add(1); for (int i = 1; i <= rowIndex; ++i) { row.add((int) ((long) row.get(i - 1) * (rowIndex - i + 1) / i)); } return row; } }
golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2023-11-28 10:18:32
func getRow(rowIndex int) []int { row := make([]int, rowIndex+1) row[0] = 1 for i := 1; i <= rowIndex; i++ { row[i] = row[i-1] * (rowIndex - i + 1) / i } return row }
golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2023-11-28 10:18:06
func getRow(rowIndex int) []int { row := make([]int, rowIndex+1) row[0] = 1 for i := 1; i <= rowIndex; i++ { for j := i; j > 0; j-- { row[j] += row[j-1] } } return row }
java 解法, 执行用时: 1 ms, 内存消耗: 39.3 MB, 提交时间: 2023-11-28 10:17:50
class Solution { public List<Integer> getRow(int rowIndex) { List<Integer> row = new ArrayList<Integer>(); row.add(1); for (int i = 1; i <= rowIndex; ++i) { row.add(0); for (int j = i; j > 0; --j) { row.set(j, row.get(j) + row.get(j - 1)); } } return row; } }
cpp 解法, 执行用时: 0 ms, 内存消耗: 6.6 MB, 提交时间: 2023-11-28 10:17:36
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> row(rowIndex + 1); row[0] = 1; for (int i = 1; i <= rowIndex; ++i) { for (int j = i; j > 0; --j) { row[j] += row[j - 1]; } } return row; } };
cpp 解法, 执行用时: 4 ms, 内存消耗: 6.8 MB, 提交时间: 2023-11-28 10:17:11
class Solution { public: vector<int> getRow(int rowIndex) { vector<vector<int>> C(rowIndex + 1); for (int i = 0; i <= rowIndex; ++i) { C[i].resize(i + 1); C[i][0] = C[i][i] = 1; for (int j = 1; j < i; ++j) { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } return C[rowIndex]; } };
java 解法, 执行用时: 1 ms, 内存消耗: 39.5 MB, 提交时间: 2023-11-28 10:16:48
class Solution { public List<Integer> getRow(int rowIndex) { List<List<Integer>> C = new ArrayList<List<Integer>>(); for (int i = 0; i <= rowIndex; ++i) { List<Integer> row = new ArrayList<Integer>(); for (int j = 0; j <= i; ++j) { if (j == 0 || j == i) { row.add(1); } else { row.add(C.get(i - 1).get(j - 1) + C.get(i - 1).get(j)); } } C.add(row); } return C.get(rowIndex); } }
golang 解法, 执行用时: 0 ms, 内存消耗: 2.1 MB, 提交时间: 2021-08-05 17:38:35
func getRow(rowIndex int) []int { ans := make([][]int, rowIndex+1) for i := range ans { ans[i] = make([]int, i+1) ans[i][0] = 1 ans[i][i] = 1 for j := 1; j < i; j++ { ans[i][j] = ans[i-1][j] + ans[i-1][j-1] } } return ans[rowIndex] }
python3 解法, 执行用时: 48 ms, 内存消耗: N/A, 提交时间: 2018-08-24 01:21:06
class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ a = [1] if rowIndex == 0: return a else: for i in range(1, rowIndex+1): a = [sum(i) for i in zip([0]+a, a+[0])] return a