[LeetCode] 119. Pascal's Triangle II

题目链接:传送门

Description

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?

Solution

题意:

求帕斯卡三角的第k行

思路:

由性质有,第 i 行的各个数分别为 \(C_k^0, C_k^1, ..., C_k^k\)

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> v;
        int n = rowIndex;
        long long ret = 1LL;
        for (int i = 0; i <= rowIndex; i++) {
            v.push_back(ret);
            ret = ret * n / (rowIndex - n + 1);
            n--;
        }
        return v;
    }
};
posted @ 2018-02-27 01:41  酒晓语令  阅读(60)  评论(0编辑  收藏  举报