您的位置:首页 > 编程语言 > C语言/C++

[leetcode-119]Pascal's Triangle II (c++)

2015-08-12 10:28 477 查看
问题描述:

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?

分析:这个可以直接利用数学方法来构造。比如n(j) = n(j-1)*(n-i)/(i+1)。注意如果直接相乘的话,很可能会导致溢出,因此需要强制转换成long型或者更高数据类型。

代码如下:0ms

[code]class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res;
        res.push_back(1);
        int prev = 1;
        for(int i = 0;i<rowIndex-1;i++){
            int val = (long)prev*(rowIndex-i)/(i+1);
            res.push_back(val);
            prev = val;
        }
        if(rowIndex>0)
            res.push_back(1);

        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: