leetcode 118 —— Pascal's Triangle

来源:互联网 发布:python 迭代器使用 编辑:程序博客网 时间:2024/04/30 13:44

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]]

思路:其实杨辉三角就是根据上一级排列得到当前排列。在这里这要使用一个一维数组即可。

用tmp记录当前的位置,给下一个使用,然后当前的位置等于前两个的和。最后再在末尾补一个1;

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




0 0