LeetCode 118, 119. Pascal's Triangle i, ii

1. 题目描述

118
Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

119
Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3,
Return [1,3,3,1].

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

2. 解题思路

我们可以参照DP 时候的思路, 但是这不是一个DP 问题。
f[i,j] 表示 第 i 行 第 j 个数据的值, 那么

f[i,j]=f[i1,j1]+f[i1,j]

也即是说, 数组中的某个值只与他的右上方和上方的值是相关的。
同时, 有要求我们只是用 O(n) 的空间复杂度, 很明显的就需要我们使用滚动数组来处理这个问题了。使用滚动数组需要注意, 避免新计算的值对我后序同行的值计算形成干扰, 在这里, 我们可以采用从后向前计算的方式来处理这个问题。

3. code

// 118 pascal i
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> res;
        vector<int> arr(numRows + 1, 0);
        arr[1] = 1;
        for (int i = 0; i != numRows; i++){
            for (int j = i + 1; j != 0; j--){
                arr[j] = arr[j - 1] + arr[j];
            }
            res.push_back(vector<int>(arr.begin() + 1, arr.begin() + i + 2));
        }

        return res;
    }
};
// 119 pascal ii
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if (rowIndex < 0)
            return vector<int>();

        int numrows = rowIndex + 1;
        vector<int> arr(numrows + 1, 0);
        arr[1] = 1;
        for (int i = 0; i != numrows; i++){
            for (int j = i + 1; j != 0; j--){
                arr[j] = arr[j - 1] + arr[j];
            }
        }

        return vector<int>(arr.begin() + 1, arr.begin() + numrows + 1);
    }
};

4. 大神代码

比我们的代码精炼些, 不过思路都是一样的

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> A(rowIndex+1, 0);
        A[0] = 1;
        for(int i=1; i<rowIndex+1; i++)
            for(int j=i; j>=1; j--)
                A[j] += A[j-1];
        return A;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值