当前位置: 代码迷 >> 综合 >> leetcode 118: Pascal's Triangle
  详细解决方案

leetcode 118: Pascal's Triangle

热度:27   发布时间:2023-12-18 00:37:12.0

问题描述:

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 arrayfor (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;}
};