LEETCODE 118

来源:互联网 发布:实验四 数据库安全管理 编辑:程序博客网 时间:2024/04/30 14:37

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

第一种思路,注意到第一行第二行和其他行的生成条件不同,第一行和第二行直接全赋值为1.

其他的第i行(i>=0),有

a[i][0]  = 1,a[i][i] = 1;(1)

a[i][j] = a[i-1][j-1]+a[i-1][j];

class Solution {public:    vector<vector<int>> generate(int numRows) {        vector<vector<int>>  fin;for (int i = 0; i < numRows ; ++i){vector<int> temp;if (i > 1){temp.push_back(1);for (int j = 1; j  < i; ++j)temp.push_back(fin[i-1][j-1] + fin[i-1][j]);temp.push_back(1);}elsefor (int j = 0; j <= i; j++)temp.push_back(1);fin.push_back(temp);}return fin;    }};
另一种思路:

不管第0行和第一行,直接将每一行的第一个和最后一个置1,其他的按照规则2:
 

class Solution {  public:      vector<vector<int> > generate(int numRows) {          // Start typing your C/C++ solution below          // DO NOT write int main() function          vector<vector<int> > res;          for(int i = 1; i<= numRows;++i){              vector<int> row(i);              row[0] = 1;  //            row[i-1] = 1;  //            for(int j = 1; j< i-1; ++j){                  row[j] = res[i-2][j-1] + res[i-2][j];  //            }              res.push_back(row);          }          return res;      }  }; 


0 0
原创粉丝点击