Pascal's Triangle <LeetCode>
Pascal's Triangle
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 class Solution { 2 public: 3 vector<vector<int>> result; 4 vector<vector<int> > generate(int numRows) { 5 result.clear(); 6 int B[numRows]; 7 int C[numRows]; 8 int count=0; 9 for(int i=0;i<numRows;i++) 10 { 11 count=0; 12 vector<int> temp; 13 temp.push_back(1); 14 B[count]=1; 15 for(int j=1;j<i;j++) 16 { 17 count++; 18 temp.push_back(B[j-1]+B[j]); 19 C[count]=B[j-1]+B[j]; 20 } 21 if(i>0) 22 { 23 temp.push_back(1); 24 25 B[count+1]=1; 26 } 27 for(int j=1;j<i;j++) 28 { 29 B[j]=C[j]; 30 } 31 result.push_back(temp); 32 } 33 return result; 34 } 35 };