leetcode 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]
]

思路:

基本上有點像斐波那契數列那樣,處理好前面兩三個情況,然後後面迭代就可以了。不過在這道題中需要注意的是下標對應的數組,0 對應的是沒有數組,1 對應的纔是一個元素的數組。

代碼:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        vector<int> temp;
        if (numRows == 0) return result;

        temp.push_back(1);
        result.push_back(temp);
        if (numRows == 1) return result;

        temp.push_back(1);
        result.push_back(temp);
        if (numRows == 2) return result;

        for (int i = 3; i <= numRows; i++)    
        {
            vector<int> layer;
            layer.push_back(1);
            vector<int> former = result[i - 2];     //found the corresponding array
            for (int j = 0; j < former.size() - 1; j++)
            {
                layer.push_back(former[j] + former[j + 1]);
            }
            layer.push_back(1);

            result.push_back(layer);
        }
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章