Pascal's Triangle
帕斯卡三角形,主要考察vector的用法。
vector<vector<int> > generate(int numRows){ vector<vector<int> > result; vector<int> tmp; result.clear(); tmp.clear(); int i,j; if(numRows == 0) return result; else if(numRows == 1){ tmp.push_back(1); result.push_back(tmp); return result; } else if(numRows == 2){ tmp.push_back(1); result.push_back(tmp); tmp.push_back(1); result.push_back(tmp); return result; } else{ tmp.push_back(1); result.push_back(tmp); tmp.push_back(1); result.push_back(tmp); for(i = 2; i < numRows; i++){ tmp.clear(); tmp.push_back(1); for(j = 1;j<=i-1;j++){ tmp.push_back(result[i-1][j-1]+result[i-1][j]); } tmp.push_back(1); result.push_back(tmp); } } return result; }
上次怎么写这个麻烦,第二次写得简练许多
1 vector<vector<int> > generate(int numRows){ 2 vector<vector<int> > res; 3 vector<int> tmp, last; 4 if(numRows == 0) 5 return res; 6 int i,j; 7 for(i = 0; i < numRows; i++){ 8 tmp = vector<int>(i+1, 0); 9 tmp[0] = 1; 10 tmp[i] = 1; 11 for(j = 1; j < i; j++) 12 tmp[j] = last[j-1] + last[j]; 13 res.push_back(tmp); 14 last = tmp; 15 } 16 return res; 17 }