公式法直接算:第0行组合数C(0,0) ;第1行C(0,1),C(1,1) ;第2行C(0,2),C(1,2),C(2,2);.......
组合数计算公式 =×(n−k+1)/k
题目:https://leetcode-cn.com/explore/featured/card/recursion-i/257/recurrence-relation/1203/
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
class Solution {
public:
vector<int> getRow(int rowIndex) {
if(rowIndex==0) return {1};
if(rowIndex==1) return {1,1};
vector<int> ans;
ans.push_back(1);
for(int i = 1;i<=rowIndex;i++) ans.push_back(Combination(rowIndex,i));
return ans;
}
int Combination(int n,int k){
long ans = 1;//运行过程中可能越界
for(int i = 1;i<=k;i++) ans = ans * (n - i + 1)/i;
return (int)ans;
}
};