leetcode【119】Pascal's Triangle II【c++,beats100%案例,多种方法】

问题描述:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


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

Example:

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

源码:

杨辉三角主要有下列五条性质:

  1. 杨辉三角以正整数构成,数字左右对称,每行由1开始逐渐变大,然后变小,回到1。
  2. n行的数字个数为n个。
  3. n行的第k个数字为组合数 C_{n-1}^{k-1}
  4. n行数字和为 2^{n-1}
  5. 除每行最左侧与最右侧的数字以外,每个数字等于它的左上方与右上方两个数字之和(也就是说,第n行第k个数字等于第 n-1 行的第 k-1 个数字与第k个数字的和)。这是因为有组合恒等式:

但是只能用O(K)的空间,所以我们每次从后向前遍历,这样保证前面的值不被覆盖。

时间100%,空间100%。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex + 1);
        res[0] = 1;
        for (int i = 1; i <= rowIndex; ++i) {
            for (int j = i; j >= 1; --j) {
                res[j] += res[j - 1];
            }
        }
        return res;
    }
};

还有一种直接从C的定义出发,比如C(7, 2)=A(7, 2) / A(2, 2), C(7, 3)=A(7, 3) / A(3, 3),因此 C(7, 3)=C(7, 2) * (7-2) / 3;

效率同样是双100%,记得用long,否则越界。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
	    vector<int> result(rowIndex+1, 0);
        long div=1, n=rowIndex;
        result[0] = 1;
        for(int i=1; i<=rowIndex; i++){
            result[i] = result[i-1]*(n--)/(div++);
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值