zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):118 Pascal's Triangle

    题目来源


    https://leetcode.com/problems/pascals-triangle/

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

    题意分析


    Input:integer

    Output:帕斯卡三角

    Conditions:帕斯卡三角数值的规律


    题目思路


    注意帕斯卡三角中,除了首尾,其他值为上一层的两个邻值的和


    AC代码(Python)

     1 class Solution(object):
     2     def generate(self, numRows):
     3         """
     4         :type numRows: int
     5         :rtype: List[List[int]]
     6         """
     7         ans = []
     8         for i in range(numRows):
     9             this = []
    10             for j in range(i+1):
    11                 this.append(1)
    12             if i > 1:
    13                 for x in range(i - 1):
    14                     this[x+1] = ans[i-1][x] + ans[i-1][x+1]
    15             print this
    16             ans.append(this)
    17         return ans
  • 相关阅读:
    mysql 主从服务器配置
    Linux命令
    Kali
    Python进阶
    性能测试工具
    sphinx搜索
    页面静态化
    PHP API接口
    线程的生命周期
    多线程的创建
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523927.html
Copyright © 2011-2022 走看看