118. Pascal's Triangle (two-dimensional vector)

Links: https://leetcode-cn.com/problems/pascals-triangle/

Given a non-negative integer numRows, generation ago with numRows Yang Hui Triangle.

In Pascal's Triangle, each number is the number of its top left and top right and.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Methods familiar two-dimensional vector for each row into a different magnitude of the vector

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;
    }
};

 

Published 84 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/104225652