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



    参考




  • 相关阅读:
    BIEE建模参考规范
    informatica 学习日记整理
    Web Service 的工作原理
    Oracle 时间差计算
    oracle基础知识
    Oracle 外连接和 (+)号的用法
    根据appId匹配项目名称
    vue技术分享-你可能不知道的7个秘密
    echarts3 迁徙图 迁入迁出
    ES6学习笔记
  • 原文地址:https://www.cnblogs.com/Bw98blogs/p/12699440.html
Copyright © 2011-2022 走看看