zoukankan      html  css  js  c++  java
  • leetcode-119-Pascal's Triangle II(生成某一行的帕斯卡三角形)

    题目描述:

     

    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.

    Example:

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

    Follow up:

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

     

    要完成的函数:

    vector<int> getRow(int rowIndex) 

     

    说明:

    1、这道题给定一个行数rowIndex,要求返回给定行数那一行的帕斯卡三角形,结果存储在vector中。要求空间复杂度不超过O(rowIndex)。

    2、做了前面的帕斯卡三角形的生成那道题目,实现这道题目也就易如反掌了。

    同样的方法,我们逐行生成每一行的帕斯卡三角形,到达指定行数时,停下来,返回vector就可以了。

    代码如下:

        vector<int> getRow(int rowIndex) 
        {
            vector<int>res={1};
            int i;
            while(rowIndex--)//如果rowIndex==0,那么不会进入循环,如果rowIndex==1,进入循环一次。
            {//while(rowIndex--)这种写法,是先判断rowIndex是不是0,如果不是那么进入循环,最后再减一;如果是,那么不进入循环。
                i=res.size()-1;
                while(i>0)
                {
                    res[i]=res[i]+res[i-1];
                    i--;
                }
                res.push_back(1);
            }
            return res;
        }
    

    上述代码实测3ms,beats 80.79% of cpp submissions。

  • 相关阅读:
    编写安全有效的 C# 代码
    模式匹配
    C#新特性
    转 C# .NET4.0 混合模式程序集异常
    win7 64位系统 注册 ocx控件
    TIFF图像文件格式详解
    GDALOGR读取数据示例 C#版本
    使用gdal C#封装库读取DEM数据
    编译C#环境下GDAL(支持HDF4、NetCDF)
    UML类图符号 各种关系说明以及举例
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9104105.html
Copyright © 2011-2022 走看看