[LeetCode] 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?

求帕斯卡三角形的一行。

利用帕斯卡三角的性质:除每行最左侧与最右侧的数字以外,每个数字等于它的左上方与右上方两个数字之和。

所以每一行都是由它的上一行计算得出。可以用一个数组就可以计算帕斯卡三角形的每一行。

从每一行的最后一个元素开始计算

res[j] = res[j] + res[j - 1]

算法过程如图:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

。。。。。。

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

 相关题目: [LeetCode] Pascal's Triangle

posted @ 2017-09-20 10:31  immjc  阅读(139)  评论(0编辑  收藏  举报