Print Yang Hui triangle:
[
[1],
[All],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Enter the number of lines printed and return the vector<vector<int> > type.
Ideas
1. My idea is to allocate vector space first, use resize, and then use subscript to access [i].
2. The other person's idea, each line is a new vector<int> cur, assigns the value after push_back to the RET.
"Other Codes"
vector<vector<int> > Generate (intnumrows) { intI, J; for(i=0; i<numrows; i++) {vector<int>cur; if(i==0) Cur.push_back (1); Else{ for(j=0; j<=i; J + +) { if(j==0|| j==i) Cur.push_back (1); Else{ intans=ret[i-1][j-1]+ret[i-1][j]; Cur.push_back (ANS); }}} ret.push_back (cur); } returnret; }
"My Code"
vector<vector<int> > Generate (intnumrows) {Vector<vector<int> >ret;
if (numrows==0)
return ret; intI, J; Ret.resize (NumRows); ret[0].push_back (1); for(i=1; i<numrows; i++) {ret[i].resize (i+1); ret[i][0]=1; Ret[i][i]=1; for(j=1; j<i; J + +) {Ret[i][j]=ret[i-1][j-1]+ret[i-1][j]; } } returnret;}
Evaluation
It always fails at first, showing that the last Test executed was {0},
Add if (numrows==0) return ret; this sentence is OK, should consider the illegal situation, so that the return of RET is an empty vector?!
OJ Practice 28--t118 Pascal's Triangle