zoukankan      html  css  js  c++  java
  • LeetCode

    Pascal's Triangle

    2014.1.8 22:44

    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]
    ]

    Solution:

      Pascal's Triangle is a typical O(n^2) dynamic programming problem. Here is the recurrence relation:

        1. f[i][0] = 1, i ∈ N

        2. f[i][i] = 1, i ∈ N

        3. f[i][j] = f[i - 1][j - 1] + f[i - 1][j], i ∈ N+, j ∈ N ∩ [0, i - 1]

      Time complexity is O(n^2). Space complexity is O(1).

    Accepted code:

     1 // Too careless, 2WA!!
     2 class Solution {
     3 public:
     4     vector<vector<int> > generate(int numRows) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         result.clear();
     8         
     9         if(numRows <= 0){
    10             return result;
    11         }
    12         
    13         int i, j;
    14         for(i = 0; i < numRows; ++i){
    15             result.push_back(vector<int>());
    16             for(j = 0; j <= i; ++j){
    17                 result[i].push_back(0);
    18             }
    19         }
    20         
    21         for(i = 0; i < numRows; ++i){
    22             result[i][i] = result[i][0] = 1;
    23         }
    24         
    25         for(i = 1; i < numRows; ++i){
    26             for(j = 1; j < i; ++j){
    27                 result[i][j] = result[i - 1][j] + result[i - 1][j - 1];
    28             }
    29         }
    30         
    31         return result;
    32     }
    33 private:
    34     vector<vector<int>> result;
    35 };
  • 相关阅读:
    【转】 MySQL高级知识(一)——基础
    inline元素的间距问题
    ES6对于数组的扩展
    JavaScript的垃圾回收机制
    call() apply() bind()
    防抖和节流
    Promise
    js的事件机制
    Javascript异步操作的异常处理
    JavaScript的事件执行机制及异步
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3511471.html
Copyright © 2011-2022 走看看