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;
        }
    };
  • 相关阅读:
    【收集】各种hack
    CSS测试实录一:display的块状元素和行内元素的试验
    【转载加工】:after伪类+content内容生成经典应用举例
    CSS测试实录二:float和标准流
    onreadyStateChange&nbsp;&nbsp;DOMContentLoaded
    Extensions
    Accessing of Rows in Silverlight DataGrid
    Linux应用程序的装载和执行
    top状态细分,进程状态
    定时器的使用和原理浅析,alarm/sleep函数
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9163020.html
Copyright © 2011-2022 走看看