zoukankan      html  css  js  c++  java
  • 118. Pascal's Triangle

    Problem:

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

    思路
    每一行由上一行产生,第一个和最后一个数为1,然后中间的数由上一行对应的数与它左边的数相加得到。也称为杨辉三角,在中国南宋数学家杨辉1261年所著的《详解九章算法》一书中出现,比欧洲的帕斯卡早了393年。

    Solution:

    vector<vector<int>> generate(int numRows) {
        if (numRows == 0)   return vector<vector<int>>{};
        vector<vector<int>> res(1, {1});
        
        for (int i = 1 ; i < numRows; i++) {
            vector<int> ans(i+1);
            ans[0] = ans[i] = 1;
            for (int j = 1; j <= i-1; j++) {
                ans[j] = res.back()[j-1] + res.back()[j];
            }
            res.push_back(ans);
        }
        return res;
    }
    

    性能
    Runtime: 0 ms  Memory Usage: 8.8 MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    jsonp 的 post
    js replace常用用法
    zindex
    x秒前
    手写jsonp
    webview 冒泡慢?
    人民币大写转阿拉伯数字
    checked
    Deadlock Troubleshooting Trace 1222
    [转]基于LUCENE实现自己的推荐引擎
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12258718.html
Copyright © 2011-2022 走看看