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] ]
很簡單的題不多說,也可以用佇列實現
#include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; typedef vector<vector<int> > VVI; VVI generate(int numRows){ VVI res; if(numRows == 0) return res; vector<int> row; row.push_back(1); res.push_back(row); if(numRows == 1) return res; row.push_back(1); res.push_back(row); if(numRows == 2) return res; for(int i = 3; i <= numRows; ++ i){ vector<int> newRow(i,1); for(int j = 1; j < i-1; ++ j){ newRow[j] = row[j]+row[j-1]; } res.push_back(newRow); row = newRow; } return res; } int main(){ VVI res = generate(5); for(int i = 0 ; i < res.size(); ++ i){ for(int j = 0 ; j < res[i].size(); ++ j){ cout<<" "<<res[i][j]; } cout<<endl; } cout<<endl; }