LeetCode #119 Pascal's Triangle II 数组 滚动数组

Description


Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

杨辉三角求解过程

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

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



思路


解法一

纯暴力。

时间复杂度:O(n^2)
空间复杂度:O(n!)

耗时 ? ms, Memory 6.5 MB, ranking ?%

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        // result
        // row[0]    1
        // row[1]    1  1
        // row[2]    1  2  1
        // row[3]    1  3  3  1
        // row[4]    1  4  1  1  1
        
        for (int i = 0; i < numRows; ++i) {  // 4
            vector<int> row(i + 1, 1);
            
            for (int j = 0; j <= i; ++j) {  // 1
                if (j && j != i) {
                    row[j] = result[i-1][j-1] + result[i-1][j];  // 4 = 1 + 3
                }
            }
            
            result.push_back(row);
        }
        
        return result;
    }
};



解法二

滚动数组思想实现空间的压缩,倒序更新数组中的元素以免上一层的结果在求解过程中被覆盖。

时间复杂度:O(n^2)
空间复杂度:O(n)

耗时 ? ms, Memory 6.1 MB, ranking ?%

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> row(rowIndex + 1, 1);

        // 滚动数组策略实现递推问题中的空间压缩(也能用于一些DP问题)
        for (int i = 0; i < rowIndex + 1; ++i) {
            for (int j = i - 1; j > 0; --j) {
                    row[j] = row[j-1] + row[j];
            }
        }

        return row;
    }
};



参考




posted @ 2020-04-14 17:30  bw98  阅读(150)  评论(0编辑  收藏  举报