119. Pascal's Triangle II
欢迎fork and star:Nowcoder-Repository-github
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?
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
解析
- 注意使用逆序累计
- 第二种方法可以利用数学的递推关系来完成:If anyone has ever learnt the mathematics equations related to the pascal triangle, they would know the following:The nth row of pascal triangle will have the following format: 1 a(1) a(2) ... a(n) here we have a(1) = n; a(k+1) = a(k) * (n-k)/(k+1).
class Solution {
public:
// 从后往前迭代
vector<int> getRow1(int rowIndex) {
vector<int> dp(rowIndex + 1, 1);
for (int i = 2; i<rowIndex + 1; i++) {
for (int j = i - 1; j>0; j--)
dp[j] = dp[j] + dp[j - 1];
}
return dp;
}
vector<int> getRow(int rowIndex) {
//A[i]=A[i-1]+A[i] 0<i<n-1
vector<int> A;
if (rowIndex < 0)
return A;
A.resize(rowIndex + 1, 0);
A[0] = 1; //第一行的数
for (int k = 1; k<=rowIndex; k++){
for (int j = k; j>0; j--){
if (j == k)
A[j] = 1; //每行结尾的数
else{
A[j] = A[j] + A[j - 1];
}
}
}
return A;
}
};
题目来源
C/C++基本语法学习
STL
C++ primer