您好,登錄后才能下訂單哦!
118. Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
題目大意:
輸入行數(shù),輸出如上圖所示的數(shù)組。(楊輝三角)
思路:
用雙vector來(lái)處理當(dāng)前行和下一行。
代碼如下:
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> result; if(numRows == 0) return result; vector<int> curVec; vector<int> nextVec; for(int i = 0;i < numRows; i++) { for(int j = 0;j<=i;j++) { if(j == 0) nextVec.push_back(1); else { if(j >= curVec.size()) nextVec.push_back(curVec[j-1]); else nextVec.push_back(curVec[j] + curVec[j-1]); } } result.push_back(nextVec); curVec.swap(nextVec); nextVec.clear(); } return result; } };
2016-08-12 09:34:50
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。