For the 2nd Pascal triangle values, we can see that we only need two additional variables to record them, so we set up a tmp array.
The overall feeling of scrolling arrays in the DP problem.
1 # include <vector> 2 # include <iostream> 3 using namespace STD; 4 5 class solution {6 public: 7 vector <int> Generate (INT numrows) {8 vector <int> res; 9 If (numrows = 0) return res; 10 for (INT I = 0; I <numrows; I ++) 11 {12 vector <int> V; V. clear (); 13 for (Int J = 0; j <= I; j ++) 14 {15 if (j = 0 | j = I) v. push_back (1); 16 if (I> 0 & J> 0 & J <I) 17 {18 v. push_back (RES [I-1] [J] + Res [I-1] [J-1]); 19} 20} 21 res. push_back (V); 22} 23 return res; // you forgot to return the result. 24} 25 vector <int> getrow (INT rowindex) {26 vector <int> res (rowindex +); 27 vector <int> TMP ); 28 // If (rowindex = 0) return vector <int> (1, 1); 29 for (INT I = 0; I <= rowindex; I ++) 30 {31 TMP [0] = 1; TMP [1] = 1; // do not put the wrong position. Put it in the inner. 32 For (Int J = 0; j <= I; j ++) 33 {34 if (j = 0 | j = I) 35 res [J] = 1; 36 IF (j> 0 & J <I) 37 {38 If (J % 2 = 0) 39 TMP [0] = res [J]; 40 else if (J % 2 = 1) 41 TMP [1] = res [J]; 42 res [J] + = TMP [1-j % 2]; 43} 44} 45} 46 Return res; 47} 48 }; 49 50 void printvv (vector <int> vv) 51 {52 for (INT I = 0; I <vv. size (); I ++) 53 {54 for (Int J = 0; j <VV [I]. size (); j ++) 55 {56 cout <VV [I] [J] <"; 57} 58 cout <Endl; 59} 60} 61 int main () 62 {63 solution s; 64 // vector <int> VV = S. generate (3); 65 vector <int> V = S. getrow (0); 66 for (INT I = 0; I <v. size (); I ++) 67 {68 cout <V [I] <"; 69} 70 // printvv (vv); 71 return 0; 72}
Leetcode-Pascal triangle I & ii