119. Pascal's Triangle II
https://leetcode.com/problems/pascals-triangle-ii/description/
当前行和上一行的i和i-1有关。为了节省空间,可以倒着遍历,那i当前和之前的元素值即上一行的i和i-1的值。
/*
* @lc app=leetcode id=119 lang=cpp
*
* [119] Pascal's Triangle II
*/
class Solution {
public:
vector<int> getRow(int rowIndex) {
++rowIndex;
if (rowIndex == 1) return {1};
vector<int> cur;
for (int i = 2; i <= rowIndex; ++i) {
cur.resize(i);
cur[0] = 1;
for (int j = i - 2; j >= 1; --j) cur[j] += cur[j - 1];
cur[i - 1] = 1;
}
return cur;
}
};
Last updated
Was this helpful?