zoukankan      html  css  js  c++  java
  • leetcode 【 Pascal's Triangle 】python 实现

    题目

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

    代码:oj测试通过 Runtime: 46 ms

     1 class Solution:
     2     # @return a list of lists of integers
     3     def generate(self, numRows):
     4         if numRows < 1:
     5             return []
     6         pascal = []
     7         first_row = [1]
     8         pascal.append(first_row)
     9         for i in range(1,numRows):
    10             tmp = []
    11             tmp.append(1)
    12             for j in range(len(pascal[i-1])):
    13                 if j == len(pascal[i-1])-1:
    14                     tmp.append(1)
    15                 else:
    16                     tmp.append(pascal[i-1][j] + pascal[i-1][j+1])
    17             pascal.append(tmp)
    18         return pascal

    思路

    排除几个special case

    然后把pascal写成如下的形式,比较容易写代码:

    [1]

    [1,1]

    [1,2,1]

    [1,3,3,1]

    [1,4,6,4,1]

  • 相关阅读:
    vuex插件
    axios
    token登录验证
    mysql模糊查询
    Koa2+Mysql搭建简易博客
    正则匹配器
    编码
    Maven学习
    防止重复提交保证幂等的几种解决方案
    策略模式优化if-else
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4229949.html
Copyright © 2011-2022 走看看