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

    118. Pascal's Triangle

    问题描述:

    Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.


    In Pascal's triangle, each number is the sum of the two numbers directly above it.

    Example:

    Input: 5
    Output:
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    解题思路:

    根据性质来做即可。

    在循环中嵌套一个循环 

    代码:

    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> ret;
            if(numRows == 0)
                return ret;
            vector<int> v;
            v.push_back(1);
            ret.push_back(v);
            for(int i = 1; i < numRows; i++){
                v.clear();
                v.push_back(1);
                for(int j = 0; j < i-1; j++){
                    v.push_back(ret[i-1][j]+ret[i-1][j+1]);
                }
                v.push_back(1);
                ret.push_back(v);
            }
            return ret;
        }
    };

    --------------------------下一道题分割线-----------------------------------------

    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.


    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?

    解题思路:

    与上题不同之处是起始层为0

    我们可以用queue在解决这个问题。

    先进先出的性质很好的帮助了我们。

    需要注意的是: 我写的内部循环只pop一次

    当进入内部循环后,最后出来还要pop一次。

    记得限定条件

    代码:

    class Solution {
    public:
        vector<int> getRow(int rowIndex) {
            vector<int> ret;
            ret.push_back(1);
            if(rowIndex == 0)
                return ret;
            queue<int> q;
            for(int i = 1; i <= rowIndex; i++){
                q.push(1);
                for(int j = 0; j < i-1; j++){
                    int n1 = q.front();
                    q.pop();
                    int n2 = q.front();
                    int n = n1 + n2;
                    q.push(n);
                }
                if(i > 1)
                    q.pop();
                q.push(1);
            }
            ret.clear();
            while(!q.empty()){
                ret.push_back(q.front());
                q.pop();
            }
            return ret;
        }
    };
  • 相关阅读:
    FreeRTOS 移植到WIN10
    Keil debug command SAVE 命令保存文件的解析
    VS2017 编译 Visual Leak Detector + VLD 使用示例
    LaTeX 中插入GIF图片
    VS2017 + Qt5 + OpenCV400 环境配置
    记一次C++编程引用obj文件作为静态库文件
    Qt 多语言支持
    vscode 解决符号无法识别的问题
    带FIFO的UART数据接收
    MySQL Connector/Python 接口 (三)
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9163020.html
Copyright © 2011-2022 走看看