Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.21 KB

0119. 杨辉三角 II [Easy] [Pascal's Triangle II].md

File metadata and controls

42 lines (30 loc) · 1.21 KB

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.

img 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,其中 k ≤ 33,返回杨辉三角的第 k 行。

思路:参考link。对于第i行,arr[i][j] = arr[i-1][j-1] + arr[i-1][j],由后往前计算,转变成arr[j] += arr[j-1]

工程代码下载

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