zoukankan      html  css  js  c++  java
  • [Leetcode 35] 118 Pascal's Trangle

    Problem:

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    Analysis:

    There two ways to solve the problem, either compute each row element separately or use inductive method.

    The latter cost much more less, so we use the latter one.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > generate(int numRows) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<vector<int> > res;
     7         vector<int> tmp;
     8         
     9         if (numRows == 0) return res;
    10         if (numRows == 1) {
    11             tmp.push_back(1);
    12             res.push_back(tmp);
    13             return res;
    14         }
    15         
    16         tmp.push_back(1);
    17         res.push_back(tmp);
    18         tmp.push_back(1);
    19         res.push_back(tmp);
    20         
    21         for (int i=2; i<numRows; i++) {
    22             vector<int> next;
    23             next.push_back(1);
    24             for (int j=1; j<i; j++) {
    25                 next.push_back(tmp[j-1] + tmp[j]);
    26             }
    27             next.push_back(1);
    28             
    29             res.push_back(next);
    30             tmp = next;
    31         }
    32         
    33         return res;
    34     }
    35 };
    View Code

    Attention:

  • 相关阅读:
    struts-spring 整合
    Spring与Struts2的整合
    three.js 3d 智慧园区
    前端框架理解
    Flutter仿照airbnb创建app
    软件、语言的安装
    python功能
    python创建项目
    安装python
    mysql的安装和使用
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096139.html
Copyright © 2011-2022 走看看