118. Pascal's Triangle

2018/04/08 leetcode 共 487 字,约 2 分钟

Title

the problem link

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5, Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Solution

就是构造这个数组嘛,注意构建vector的方式哈

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

Search

    Table of Contents