Leetcode 119: Pascal‘s Triangle II

119. Pascal's Triangle II

Easy

Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.

Notice that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Follow up:

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

 

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Constraints:

  • 0 <= rowIndex <= 33

解法1:

纯数学法。杨辉三角形每行就是$C_{n}^{i}$, $i=0..n$,
比如第3行(从0开始),$C_3^0=1$, $C_3^1=3$, $C_3^2=3$, $C_3^3=1$.
那么,我们怎么从$C_n^{i-1}$ => $C_n^i$呢?
根据$C_n^i = n!/(i!*(n-i)!)$可得$C_n^i=C_n^{i-1}*(n-i+1)/i $
代码如下:
注意coeff中间可能会越界,所以要开long long。
时间复杂度O(n),空间复杂度O(1)。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res;
        long long coeff = 1;
        res.push_back(1);
        for (int i = 1; i <= rowIndex; i++) {
            coeff = coeff * (rowIndex - i + 1) / i;
            res.push_back((int)coeff) ;
        }
        return res;
    }
};

解法2:
迭代 。我用了两个循环,而且还有一个辅助vector。时间复杂度O(n^2),空间复杂度O(n),效率不高。

```
#include <iostream>
#include <vector>

using namespace std;

vector<int> getRow(int rowIndex) {
    if (rowIndex==0) return vector<int>(1,1);
    if (rowIndex==1) return vector<int>(2,1);

    vector<int> result(rowIndex+1, 1);

    for (int i=2; i<=rowIndex; ++i) {
        vector<int> prevResult=result;
        for (int j=1; j<i; ++j) {
            result[j]+=prevResult[j-1];
        }
    }

    return result;
}


int main()
{
    for (int k=0; k<=4; ++k) {
        vector<int> a=getRow(k);
        for (auto i:a) cout<<i<<" ";
        cout<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值