118. 杨辉三角(二维向量)

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

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

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

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

熟悉二维向量每行插入不同大小向量的方法

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector< vector<int> > ans;
        for(int i = 0; i < numRows; ++i)
        {
            ans.push_back(vector<int>(i+1, 1));  
        }
        for(int i = 2; i < numRows; ++i)
        {
            for(int j = 1; j < i; ++j)
            {
                ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];
            }
        }
        return ans;
    }
};
发布了84 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43569916/article/details/104225652
今日推荐