119. Pascal's Triangle II

Problem:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

PascalTriangle
In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

思路
本来求出第k行是很简单的,但是题目要求用O(k)的空间复杂度,就说明只能申请一个大小为k的数组,然后不断更新,得到第k行的值。在纸上画一下就出来了。
注意的是更新的时候要从右往左更新,因为如果从左往右更新的话新的值会覆盖原来数组的值,产生错误的结果。

Solution:

vector<int> getRow(int rowIndex) {
    vector<int> res(rowIndex+1, 0);
    res[0] = 1;
    
    for (int i = 1; i < rowIndex+1; i++) {  //i为帕斯卡三角的行数
        for (int j = i; j >= 1; j--) {    //j为某个三角的具体元素,注意一定要从右往左赋值,否则会产生覆盖
            res[j] += res[j-1];
        }
    }
    return res;
}

性能
Runtime: 4 ms  Memory Usage: 8.4 MB

posted @ 2020-02-04 20:05  littledy  阅读(78)  评论(0编辑  收藏  举报