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 #include "stdafx.h" 2 #include <string> 3 #include <vector> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 8 class Solution 9 { 10 public: 11 vector<vector<int>> generate(int numRows) 12 {//生成帕斯卡三角形 13 //找规律 14 vector<vector<int>> res; 15 if(numRows<=0) 16 return res; 17 vector<int> front; 18 for(int i=0; i<numRows; i++) 19 { 20 vector<int> tmp; 21 for(int j=0; j<i+1; j++) 22 { 23 if(j==0 || j==i) 24 tmp.push_back(1); 25 else 26 { 27 tmp.push_back(front[j]+front[j-1]);//又是i、j傻傻分不清楚!!! 28 } 29 } 30 front = tmp; 31 res.push_back(tmp); 32 } 33 return res; 34 } 35 }; 36 37 int main() 38 { 39 Solution sol; 40 int numRows; 41 vector<vector<int>> res; 42 while(cin >> numRows) 43 { 44 cout << numRows<<" : "<<endl; 45 res = sol.generate(numRows); 46 for(const auto &i : res) 47 { 48 for(const auto &j : i) 49 cout << j << " "; 50 cout << endl; 51 } 52 cout <<"--------------"<<endl; 53 } 54 }
No.118 Pascal's Triangle
时间: 2024-10-25 13:15:27