溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

leetCode 118. Pascal's Triangle 數(shù)組 (楊輝三角)

發(fā)布時(shí)間:2020-07-06 16:34:12 來(lái)源:網(wǎng)絡(luò) 閱讀:904 作者:313119992 欄目:編程語(yǔ)言

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

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI