leetcode-118-119 杨辉三角/II

118. 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

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

简单思路:杨辉三角我们很熟悉了,两端都是1,中间的数字是上一行左上和右上值的和。至于怎么算,就很简单了。

next[i] = top[i] + top[i-1]

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        if(numRows <= 0)
            return {};
        else if(numRows == 1)
            return {{1}};
        else if(numRows == 2)
            return {{1}, {1, 1}};
        vector<vector<int>> res = {};
        res.push_back({1});
        res.push_back({1, 1});
        vector<int> top = {1, 1};
        for(int i=3; i<= numRows; i++)
        {
            vector<int> next = vector<int>(i, 0);
            *(next.begin()) = 1;
            *(next.end()-1) = 1;
            for(int j=1; j<i-1; j++)
                next[j] = top[j] + top[j-1];
            res.push_back(next);
            top = next;
        }
        return res;
    }
};

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

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

示例:

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

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if(rowIndex == 0)
            return {1};
        else if(rowIndex == 1)
            return {1, 1};
        vector<int> top = {1, 1};
        vector<int> res;
        for(int i=2; i<=rowIndex+1; i++)
        {
            res = vector<int>(i, 0);
            *(res.begin()) = 1;
            *(res.end()-1) = 1;
            for(int j=1; j<i-1; j++)
                res[j] = top[j] + top[j-1];
            top = res;
        }
        return res;
    }
};
posted @ 2019-11-18 11:19  yocichen  阅读(307)  评论(0)    收藏  举报