对于第2个pascal triangle,通过观察可以发现,其实只需要2个额外的变量来记录,于是就设了个tmp数组。
整体有点DP问题中的滚动数组的感觉。
1 #include <vector> 2 #include <iostream> 3 using namespace std; 4 5 class Solution { 6 public: 7 vector<vector<int> > generate(int numRows) { 8 vector<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;///////////忘了返回了,一直找不出错来。 24 } 25 vector<int> getRow(int rowIndex) { 26 vector<int> res(rowIndex+1,0); 27 vector<int> tmp(2,0); 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;//别放错位置。之前放到内层的for里了。 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<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<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 }