118. Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

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

方法1:暴力求解,两个for循环分别添加行和列。

class Solution {
public:
    vector> generate(int numRows) {
        vector> res;
        if(numRows==0) return res;
        else res.push_back({1});
        for(int i=1;i tp;
            for(int j=0;j<=i;j++){
                if(j==0) tp.push_back(res[i-1][0]);
                else if(j==i) tp.push_back(res[i-1][i-1]);
                else tp.push_back(res[i-1][j-1]+res[i-1][j]);
            }
            res.push_back(tp);
        }
        return res;
    }
};

Tips:注意i,j的使用

你可能感兴趣的:(算法)