Leetcode:Pascal's Triangle 杨辉三角

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


分析:
这题完全就是模拟题,掌握两点就可以:
1. 不要被它的这个金字塔排列形式迷惑了,而是要把它按照数组形式对齐排列
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
 

 


2. 重新排列之后,其中规律就很容易看出来了,每一行首尾都是1,其余就是 a[i][j] = a[i-1][j-1] + a[i-1][j]
class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        assert(numRows >= 0);
        vector<vector<int> > res(numRows, vector<int>(0, 0));
        for (int i = 0; i < numRows; ++i) {
            for (int j = 0; j <= i; ++j) {
                if (i == 0) {
                    res.at(i).push_back(1);
                } else {
                    if (j == 0 || j == i) {
                        res.at(i).push_back(1);
                    } else {
                        res.at(i).push_back(res.at(i-1).at(j-1) + res.at(i-1).at(j));
                    }
                }
            }
        }
        return res;
    }
};

 

Pascal's Triangle II

 

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

 

分析:在第一题中,我们分配了二维数组,现在要求O(k)空间复杂度

这其实也很好办,注意 index 为 k时,返回的数组长为 k+1,我们就可以只分配 k+1 长度数组即可
其实我们在计算每一行的过程中,都是利用上一行的暂存结果,然后覆盖上一行的结果

这样我们就可以只分配 k+1 长度数组,然后每一行计算时模拟 当前行覆盖上一行暂存结果的这一过程。
唯一需要注意的就是:在计算当前行的过程中,因为 a[i][j] = a[i-1][j-1] + a[i-1][j]
如果我们从前往后计算,则会用 a[i][j] 覆盖掉原来的 a[i-1][j] ,而之后计算 a[i][j+1] 的时候我们仍然需要的是 上一行的 a[i-1][j] ,这时就会出错
我们只需要反过来,从后向前计算即可,因为 计算后面是依赖前面,而计算前面是不依赖后面的.....
class Solution {
public:
    vector<int> getRow(int rowIndex) {
        assert(rowIndex >= 0);
        vector<int> res(rowIndex+1, 0);
        for (int i = 0; i <= rowIndex; ++i) {
            for (int j = i; j >= 0; --j) {
                if (i == 0) {
                    res.at(i) = 1;
                } else {
                    if (j == 0) {
                        res.at(j) = 1;
                    } else {
                        res.at(j) = res.at(j) + res.at(j-1);
                    }
                }
            }
        }
        return res;
    }
};
 

 




你可能感兴趣的:(LeetCode)