给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
分析:
可以将整个杨辉三角算出来
杨辉三角有一个性质,第m排的第n个数字是Cmn,m是下标,n是上标,但是这么算会超过int最大数
所以还是老老实实把每一行都算出来吧!!!!!!!!!!!!
class Solution {
public:
vector<int> getRow(int rowIndex) {
/*
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
result[i][j] = result[i-1][j] + result[i-1][j-1];
*/
vector<int> result;
result.push_back({1});
for(int i=1; i<= rowIndex; i++){
result.insert(result.begin(),0);
for(int j=0; j<=i; j++){
int num = 0;
num += (j==i)?0:result[j+1];
num += result[j];
result[j] = num;
}
}
return result;
}
};
这个就是会超时的那种
class Solution {
public:
vector<int> getRow(int rowIndex) {
// 鸣少曰:杨辉三角是这样的
/*
1
C10 C11
C20 C21 C22
C30 C31 C32 C33
*/
vector<int> result;
// 全部都算,只算一般会更省时,因为另一半是相等的
for(int i=0; i<=rowIndex; i++){
result.push_back(C_n_m(i,rowIndex));
}
return result;
}
// 返回 C,m为底数,n为上标
int C_n_m(int n,int m){
if(n > m/2)
n = m-n;
if(n==0)
return 1;
// 分子
int molecule = 1;
for(int i=0; i<n; i++){
molecule *= m;
m --;
}
// 分母
int denominator = 1;
for(int j=1; j<=n; j++){
denominator *= j;
}
return molecule/denominator;
}
};
的计算时间