2019-08-20 杨辉三角

作者: Antrn | 来源:发表于2019-08-20 21:24 被阅读0次

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

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

    示例:

    输入: 5

    输出:

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]
    
    C++
    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            if(numRows == 0) return {};
            vector<vector<int>> matrix;
            for(int i=0;i<numRows;i++){
                vector<int> row;
                for(int j=0;j<i+1;j++){
                    if(i == j || j == 0){
                        row.push_back(1);
                    }
                    else{
                        row.push_back(matrix[i-1][j-1]+matrix[i-1][j]);
                    }
                }
                matrix.push_back(row);
            }
            return matrix;
        }
    };
    

    相关文章

      网友评论

        本文标题:2019-08-20 杨辉三角

        本文链接:https://www.haomeiwen.com/subject/ubbmsctx.html