导航

LeetCode 119. Pascal's Triangle II

Posted on 2016-08-08 13:37  CSU蛋李  阅读(124)  评论(0编辑  收藏  举报

帕斯卡三角形也叫杨辉三角,是二项式展开的系数。我们只要记住下面的值等于上面的相对应的值和其左侧的值相加得到的即可

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<int> getRow(int rowIndex) {
        vector<int> result(rowIndex+1,0);
        if (rowIndex == 0)
        {
            result[0]=1;
            return result;
        }
        result[0] = 1;
        result[1] = 1;
        for (int i = 2;i <= rowIndex;++i)
        {
            vector<int> temp(result);
            result[i] = 1;
            for (int j = 1;j < i;++j)
            {
                result[j] = temp[j] + temp[j - 1];
            }
            
        }
        return result;
    }
};