leetcode119 - Pascal's Triangle II - easy

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.


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+1大小的res vector来track每层的值的时候怎么个修改顺序。
新一层除了头尾,row[j]等于上一层的row[j]+上一层的row[j-1]。因为我们要原地改,如果从左往右更新,那改到j的时候j-1已经是当前这层的值了,上一层的值被覆盖了也没法获取了。所以要从右往左更新,j反正只用到j和j-1, j+1改了对它也没影响。同时每层起始的时候row.back()都是0,因为上一层没这个位置的,row[j] += row[j-1]也确保了最右边都是1. 每层的循环从j=i到j>=1为止。
 
实现:
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        
        vector<int> res(rowIndex+1);
        res[0] = 1;
        
        for (int i=1; i<=rowIndex; i++){
            for (int j=i; j>=1; j--){
                res[j] = res[j] + res[j-1];
            }
        }
        
        return res;

    }
};

 

你可能感兴趣的:(leetcode119 - Pascal's Triangle II - easy)