Pascal's Triangle I, II

题目链接

https://leetcode.com/problems/pascals-triangle/

https://leetcode.com/problems/pascals-triangle-ii/

这两道题都是数组操作,需要注意的是II在I的基础上使用滚动数组存储过往的中间结果,这个思想可以注意一下,一些DP的题目也会用到

I's code

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

II's code

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex + 1, 0);
        res[0] = 1;
        for(int i = 1; i <= rowIndex; i++) {
            for(int j = i; j > 0; j--) {
                res[j] = res[j - 1] + res[j];
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/walcottking/p/4430838.html