Solution 1
杨辉三角,模拟题。基本模拟规则:
- 首尾为1
- 中间部分来自上一层结果相邻加和
- 时间复杂度: O ( # R o w 2 ) O(\#Row^2) O(#Row2),即行数的平方
- 空间复杂度: O ( 1 ) O(1) O(1),过程中的临时变量引用自结果,因此实际没有占用额外空间
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans;
for(int i = 1; i <= numRows; ++i) {
vector<int> temp(i);
// 首末置为1
temp[0] = 1;
temp[i - 1] = 1;
// 中间部分,沿着上一层,相邻两个加和
if (i > 2) {
auto prev = ans.back();
for (int j = 1; j < i - 1; ++j) {
temp[j] = prev[j - 1] + prev[j];
}
}
ans.push_back(temp);
}
return ans;
}
};
Solution 2
Solution 1的Python实现
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
ans = []
for i in range(1, numRows + 1):
temp = [0] * i
temp[0] = 1
temp[-1] = 1
if i > 2:
for j in range(1, i - 1):
# print(j, len(ans[-1]))
temp[j] = ans[-1][j - 1] + ans[-1][j]
ans.append(temp)
return ans