zoukankan      html  css  js  c++  java
  • 119. Pascal's Triangle II

    Problem:

    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.

    PascalTriangle
    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?

    思路
    本来求出第k行是很简单的,但是题目要求用O(k)的空间复杂度,就说明只能申请一个大小为k的数组,然后不断更新,得到第k行的值。在纸上画一下就出来了。
    注意的是更新的时候要从右往左更新,因为如果从左往右更新的话新的值会覆盖原来数组的值,产生错误的结果。

    Solution:

    vector<int> getRow(int rowIndex) {
        vector<int> res(rowIndex+1, 0);
        res[0] = 1;
        
        for (int i = 1; i < rowIndex+1; i++) {  //i为帕斯卡三角的行数
            for (int j = i; j >= 1; j--) {    //j为某个三角的具体元素,注意一定要从右往左赋值,否则会产生覆盖
                res[j] += res[j-1];
            }
        }
        return res;
    }
    

    性能
    Runtime: 4 ms  Memory Usage: 8.4 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    java工程师要求
    系统架构设计师知识模块
    Mybatis使用训练
    项目—视频直播系统
    [数算]概率
    查看镜像文件
    Hadoop启动命令
    Hadoop启动命令
    HDFS设置配额管理
    HDFS设置配额管理
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12260870.html
Copyright © 2011-2022 走看看