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;
        }
    };
    



    参考




  • 相关阅读:
    env文件的作用
    Ubuntu 卸载wine
    Linux配置yaf3.x.x环境
    yaf中使用Cli模式,也就是定时器
    Yaf 在Bootstrap中注册变量,然后在其他地方进行使用!
    yaf 查看配置
    yaf配置通用函数
    一个严谨的接口调用
    后台基础表
    tensorflow环境搭建
  • 原文地址:https://www.cnblogs.com/Bw98blogs/p/12699440.html
Copyright © 2011-2022 走看看