zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    



    参考




  • 相关阅读:
    LeetCode153.寻找旋转排序数组中的最小值
    LeetCode88.合并两个有序数组
    分析树
    LeetCode119.杨辉三角 II
    ssh传输文件
    ubuntu arm妙算加载cp210x驱动
    terminator终端工具
    ros使用rplidar hector_mapping建地图
    launch文件
    eclipse配置ros cakin编译环境
  • 原文地址:https://www.cnblogs.com/Bw98blogs/p/12699440.html
Copyright © 2011-2022 走看看