118. Pascal's Triangle

欢迎fork and star:Nowcoder-Repository-github

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

解析

  • 前面的特殊情况可以放在循环当中处理。
class Solution_118 {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> vecs;
        vector<int> vec;
        if (numRows==0)
        {
            return vecs;
        }
        //if (numRows==1)  //放在循环中
        //{
        //  vec.push_back(1);
        //  vecs.push_back(vec);
        //  return vecs;
        //}
        //if (numRows == 2)
        //{
        //  vec.push_back(1);
        //  vecs.push_back(vec);
        //  vec.clear();
        //  vec.push_back(1);
        //  vec.push_back(1);
        //  vecs.push_back(vec);
        //  
        //  return vecs;
        //}
        //vec.push_back(1);
        //vecs.push_back(vec);
        //vec.clear();
        //vec.push_back(1);
        //vec.push_back(1);
        //vecs.push_back(vec);
        //vec.clear();
        for (int i = 1; i <= numRows;i++)
        {
            vec.resize(i,1);   //vector<int> tmp(i,1);
            for (int j = 1; j < vec.size()-1; j++)
            {
                vec[j] = vecs[i - 2][j - 1] + vecs[i - 2][j];
            }
            vecs.push_back(vec);
        }

        return vecs;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8206938.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞