[Leetcode]Pascal's Triangle

来源:互联网 发布:电脑语音同声翻译软件 编辑:程序博客网 时间:2024/06/15 22:52

// 比较直白的一道题。缓存一个last,memory为O(n),把前一排数字存入以确定下一排数字

class Solution {

public:
    vector<vector<int> > generate(int numRows) {
        vector<int> temp;
        vector<int> last;
        temp.push_back(1);
        vector<vector<int>> result;
        if(numRows==0)
        return result;
        //if(numRows==1)
        result.push_back(temp);
        last=temp;
        temp.clear();
        for(int i=2;i<=numRows;i++)
        {
            for(int j=1;j<=i;j++)
            {
                if(j==1)
                temp.push_back(1);
                else if(j==i)
                temp.push_back(1);
                else
                temp.push_back(last[j-2]+last[j-1]);
            }
            result.push_back(temp);
            last=temp;
            temp.clear();
        }
        return result;
    }
};
0 0