[LeetCode] 119 Pascal's Triangle II

这是一道很简单的题目,输出杨辉三角具体的某一行。很简单的一道题,但题目有要求只能用O(k)的额外空间,因此我们就不能把这个杨辉三角生成出来。

这是我原来的做法:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<vector<int>> temp(rowIndex + 1);
        for (int i = 0; i <= rowIndex; i++) {
            temp[i] = vector<int>(i + 1);
        } 
        temp[0][0] = 1;
        for (int i = 1; i <= rowIndex; i++) {
            for (int j = 0; j < temp[i].size(); j++) {
                if (j == 0) temp[i][j] = temp[i - 1][j];
                if (j == temp[i].size() - 1) temp[i][j] = temp[i - 1][j - 1];
                else temp[i][j] = temp[i - 1][j] + temp[i - 1][j - 1];
            }
        }
        return temp[rowIndex];
    }
};

要只用O(k)的额外空间,就要从后面开始遍历起。这种节省空间的方法(把二维转为一维数组)在很多地方都用到了。

代码如下:

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 = rowIndex; j >= 0; j--) {
                if (j == 0) res[j] = res[j];
                else res[j] = res[j] + res[j - 1];
            }
        }
        return res;
    }
};

 

posted @ 2017-11-30 21:18  fengzw  阅读(172)  评论(0编辑  收藏  举报