杨辉三角的解法
要求返回前n行的楊輝三角所有值
點擊查看更多通信與專業知識
118. 楊輝三角
難度簡單493
給定一個非負整數?numRows,生成楊輝三角的前?numRows?行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5 輸出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1] ]按照定義直接寫就行。每進入下一行就重新增加一個對應個數的數組,并將第一個和最后一個置為1,其余位res[n][i] = res[n-1][i-1] + res[n-1][i]。由于對稱,還可以對其進行優化。
?
// class Solution { // public: // vector<vector<int>> generate(int numRows) { // vector<vector<int>> res; // if(numRows == 0) return res; // for(int n = 0; n < numRows; n++){ // res.push_back(vector<int>(n+1)); // res[n][0] = res[n][n] = 1; // for(int i = 1; i <= n/2; i++){//可以只計算前一半 // res[n][n-i] = res[n][i] = res[n-1][i-1] + res[n-1][i]; // } // } // return res; // } // };class Solution { public:vector<vector<int>> generate(int numRows) {vector<vector<int>> res;if(numRows == 0) return res;for(int n = 0; n < numRows; n++){res.push_back(vector<int>(n+1));res[n][0] = res[n][n] = 1;for(int i = 1; i < n; i++){//算整行的話就不能取到nres[n][i] = res[n-1][i-1] + res[n-1][i];}}return res;} };?
總結
- 上一篇: 快慢指针寻找循环节点
- 下一篇: vba代码编程800例_VBA编程常用过