LeetCode Pascal's Triangle II

Pascal's Triangle II

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?

计算第k行的杨辉三角序列,如果用数学公式计算,会有溢出的问题,这里采用比较巧妙的方式,增量式求第k行的元素。

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

 

posted @ 2014-12-02 20:28  ElephantKing  阅读(92)  评论(0编辑  收藏  举报