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;
        }
    };
  • 相关阅读:
    SpringMVC 通过post接收form参数或者json参数
    Web验证码图片的生成-基于Java的实现
    springmvc防止表单重复提交demo
    MyBatis多表映射demo
    mybatis配置ehcache缓存
    Oracle数据库Where条件执行顺序
    省选模拟10
    省选模拟8
    省选模拟9
    省选模拟7
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9163020.html
Copyright © 2011-2022 走看看