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:

  • 相关阅读:
    saltstack配置管理之YAML(二)
    自动化运维之saltstack 简单用法(一)
    异常处理,枚举,泛型
    面向对象二
    面向对象
    python面向对象
    方法(函数),内存空间,数组
    for循环,while循环,do while循环
    if判断,switch语句
    运算符
  • 原文地址:https://www.cnblogs.com/freeneng/p/3096139.html
Copyright © 2011-2022 走看看