导航

LeetCode 118. Pascal's Triangle

Posted on 2016-08-08 15:10  CSU蛋李  阅读(145)  评论(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]
]
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> fresult;
        if (numRows == 0)
        {
            return fresult;
        }
        vector<int> result(numRows , 0);
        result[0] = 1;
        result[1] = 1;
        vector<int> temp(1, 1);
        fresult.insert(fresult.cend(), temp);
        if (numRows == 1)
        {
            return fresult;
        }
        vector<int> temp1(2, 1);
        fresult.insert(fresult.cend(), temp1);
        if (numRows == 2)
        {
            return fresult;
        }
        for (int i = 2;i <= numRows-1;++i)
        {
            vector<int> temp(result);
            result[i] = 1;
            for (int j = 1;j < i;++j)
            {
                result[j] = temp[j] + temp[j - 1];
            }
            vector<int> temp1(result.begin(), result.begin() + i + 1);
            fresult.insert(fresult.end(), temp1);
        }
        return fresult;
    }
};