LeetCode: Pascal's Triangle

来源:互联网 发布:delphi编译传奇源码 编辑:程序博客网 时间:2024/05/16 09:11

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

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


Round 2:

class Solution {public:    vector<vector<int> > generate(int numRows) {        vector<vector<int> > result;for(int i = 1; i <= numRows; i++){vector<int> cur;if(result.empty()){cur.push_back(1);result.push_back(cur);}else{for(int j = 0; j < i; j++){int temp = 0;if(j-1 >= 0)temp += result.back()[j-1];if(j < result.back().size())temp += result.back()[j];cur.push_back(temp);}result.push_back(cur);}}return result;    }};


Round 3:

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






0 0