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]
]
題目鏈接

題意:

給一個行數,代表的是Pascal三角形的層數,要求用vector存儲Pasicl三角,並將其返回。

通過觀察可以得知,Pasicl三角的第i層有i個元素,且對於非首行,非首列,非末列的元素而言,元素的值等於上一層左右連個節點之和,即

nums[i][j] = nums[i-1][j-1] + nums[i-1][j]。

代碼如下:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int> > ans;
        for (int i = 0; i < numRows; i ++) {
            vector<int> temp;
            if (i == 0) temp.push_back(1);
            else {
                for (int j = 0; j <= i; j ++) {
                    if (j == 0) {
                        temp.push_back(ans[i-1][j]);
                    }
                    else if (j == i) {
                        temp.push_back(ans[i-1][j-1]);
                    }
                    else {
                        temp.push_back(ans[i-1][j-1] + ans[i-1][j]);
                    }
                }
            }
            ans.push_back(temp);
        }
        return ans;
    }
};


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