欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【leetcode】119. Pascal's Triangle II

程序员文章站 2022-04-01 12:08:29
...

题目:
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.

【leetcode】119. Pascal's Triangle II

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


思路:
直接看图就好。规律很明显。
【leetcode】119. Pascal's Triangle II


代码实现:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> ans(rowIndex+1, 1);
        if (rowIndex <= 1){
            return ans;
        }
        
        for (int i = 2; i <= rowIndex; ++i){
            int pre = 1;
            for (int j = 1; j < i; ++j){
                int t = ans[j];
                ans[j] += pre;
                pre = t;
            }   
        }
        
        return ans;
    }
};

【leetcode】119. Pascal's Triangle II