【LeetCode】119. 杨辉三角 II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuqiuai/article/details/82983115

题目链接https://leetcode-cn.com/problems/pascals-triangle/description/

题目描述

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

在这里插入图片描述

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例

输入: 3
输出: [1,3,3,1]

进阶:

你可以优化你的算法到 O(k) 空间复杂度吗?

解决方法

使用滚动数组

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        
        // 使用滚动数组
        
        vector<int> result(rowIndex+1);
        
        if (rowIndex==0) return {1};
        
        for(int i=0;i<=rowIndex;i++){
            result[i]=1;
            for (int j = i - 1; j >= 1; j--){ 
                result[j] += result[j - 1];
            }
        }
        
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/fuqiuai/article/details/82983115