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;
        }
    };
  • 相关阅读:
    win7 64bit下使用PL/SQL Developer连接Oracle
    C#高级开发之 特性(Attribute)三
    K3单据表结构描述和相关关联SQL语句以及金蝶插件相关说明
    K3老单插件控制字段显示
    金蝶K3插件开发-控制单据焦点(BOS单据、工业单据)
    K3 单据,单据体自定义字段显示及时库存
    C#高级开发之反射(Reflection)二
    C#高级开发之泛型一
    python学习——协程
    python学习——线程
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9163020.html
Copyright © 2011-2022 走看看