LeetCode 118杨辉三角(C++)

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

思路:两层循环,依次计算每个元素,时间复杂度O(n^2)

我的解答:

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

执行用时为0ms的范例:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        
        vector<vector<int> > rst;

        if (numRows == 0)
            return rst;

        vector<int> tmp(1, 1);
        rst.push_back(tmp);

        for (int i = 1; i < numRows; i++)
        {
            vector<int> tmp(1, 1);
            vector<int> last_rst = rst[i - 1];
            for (int j = 1; j <= i / 2; j++)
            {
                tmp.push_back(last_rst[j] + last_rst[j - 1]);
            }

            for (int j = i / 2 + 1; j < i + 1; j++)
            {
                tmp.push_back(tmp[i - j]);
            }

            rst.push_back(tmp);
        }

        return rst;
    }
};

 

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/u010653518/article/details/84252354
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞