我的思路后来被证实是比较慢哈,思路很简单,递归地一行一行地往里插。是这样的:
vector<vector<int>> generate(int numRows) { if (numRows < 1){ return vector<vector<int>>(); } if (numRows == 1){ return vector<vector<int>>{vector<int>{1}}; } auto&& lastLine = generate(numRows - 1); vector<int> thisLine; for (int i = 0; i != numRows - 1; ++i){ if (i == 0){ thisLine.push_back(1); } else{ thisLine.push_back(lastLine[numRows - 2][i - 1] + lastLine[numRows - 2][i]); } } thisLine.push_back(1); lastLine.push_back(thisLine); return lastLine; }
通过测试用了 4ms, 仍不是最好。出于习惯,我查看了投票数最高的方法,发现他的思路是迭代地填充:
vector<vector<int> > generate(int numRows) { vector<vector<int>> r(numRows); for (int i = 0; i < numRows; i++) { // Set enough places. r[i].resize(i + 1); // Set the values of the edge. r[i][0] = r[i][i] = 1; // Evalue values in the middle. for (int j = 1; j < i; j++) r[i][j] = r[i - 1][j - 1] + r[i - 1][j]; } return r; }
注释是我加的,所以可能处于中国人看不懂,外国人看不明白的情况。希望谅解,领会精神哈。
时间: 2024-08-08 17:46:22