【LeetCode】118 & 119 - Pascal's Triangle & Pascal's Triangle II

时间:2023-03-09 00:18:45
【LeetCode】118 & 119 - Pascal's Triangle & Pascal's Triangle II

118 - Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Solution:

class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret;
if(numRows==)return ret;
vector<int> vec(,);
ret.push_back(vec);
int i=;
while(i<numRows){
vec.clear();
vec.push_back();
for(int j=;j<ret[i-].size();j++){
vec.push_back(ret[i-][j-]+ret[i-][j]);
}
vec.push_back();
ret.push_back(vec);
i++;
}
return ret;
}
};

119 - Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

Solution:

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> vec(,);
vector<vector<int>> ret;
ret.push_back(vec);
int i=;
while(i<=rowIndex){
vec.clear();
vec.push_back();
for(int j=;j<ret[i-].size();j++){
vec.push_back(ret[i-][j-]+ret[i-][j]);
}
vec.push_back();
ret.push_back(vec);
i++;
}
return vec; //or return ret[rowIndex];
}
};