leetCode119.Pascal'sTriangleII数组

119. Pascal's Triangle II

睢县ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!

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?

代码如下:(使用双数组处理,未优化版)

class Solution {
public:
    vector getRow(int rowIndex) {
        vector curVec;
        vector nextVec;
        if(rowIndex < 0)
            return curVec;
        for(int i = 0;i <= rowIndex; i++)
        {
            for(int j = 0;j<=i;j++)
            {
                if(j == 0)
                    nextVec.push_back(1);
                else
                {
                    if(j >= curVec.size())
                        nextVec.push_back(curVec[j-1]);
                    else
                        nextVec.push_back(curVec[j] + curVec[j-1]);
                }
            }
            curVec.swap(nextVec);
            nextVec.clear();
        }
        return curVec;
    }
};

使用思路:

The basic idea is to iteratively update the array from the end to the beginning.

从后到前来更新结果数组。

参考自:https://discuss.leetcode.com/topic/2510/here-is-my-brief-o-k-solution

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

2016-08-12 10:46:10


分享名称:leetCode119.Pascal'sTriangleII数组
当前路径:http://azwzsj.com/article/piigej.html