1. 题目描述
118
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]
]119
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?
2. 解题思路
我们可以参照DP 时候的思路, 但是这不是一个DP 问题。
记
f[i,j]
表示 第 i 行 第 j 个数据的值, 那么
f[i,j]=f[i−1,j−1]+f[i−1,j]
也即是说, 数组中的某个值只与他的右上方和上方的值是相关的。
同时, 有要求我们只是用 O(n) 的空间复杂度, 很明显的就需要我们使用滚动数组来处理这个问题了。使用滚动数组需要注意, 避免新计算的值对我后序同行的值计算形成干扰, 在这里, 我们可以采用从后向前计算的方式来处理这个问题。
3. code
// 118 pascal i
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
vector<int> arr(numRows + 1, 0);
arr[1] = 1;
for (int i = 0; i != numRows; i++){
for (int j = i + 1; j != 0; j--){
arr[j] = arr[j - 1] + arr[j];
}
res.push_back(vector<int>(arr.begin() + 1, arr.begin() + i + 2));
}
return res;
}
};
// 119 pascal ii
class Solution {
public:
vector<int> getRow(int rowIndex) {
if (rowIndex < 0)
return vector<int>();
int numrows = rowIndex + 1;
vector<int> arr(numrows + 1, 0);
arr[1] = 1;
for (int i = 0; i != numrows; i++){
for (int j = i + 1; j != 0; j--){
arr[j] = arr[j - 1] + arr[j];
}
}
return vector<int>(arr.begin() + 1, arr.begin() + numrows + 1);
}
};
4. 大神代码
比我们的代码精炼些, 不过思路都是一样的
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> A(rowIndex+1, 0);
A[0] = 1;
for(int i=1; i<rowIndex+1; i++)
for(int j=i; j>=1; j--)
A[j] += A[j-1];
return A;
}
};