zoukankan      html  css  js  c++  java
  • 23.leetcode118_pascal's_traingle

    1.题目描述

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

    给出一个numRows,输出1~numRows层的杨辉三角

    2.题目分析

    ①第一层为[1]②第二层为[1,1]③第n(n>2)层,[1...n[i]=(n-1)[i]+(n-1)[i-1]...1]

    3.解题思路

     1 class Solution(object):
     2     def generate(self, numRows):
     3         """
     4         :type numRows: int
     5         :rtype: List[List[int]]
     6         """
     7         def rows(nums,traingle):
     8             l=len(traingle) #取当前杨辉三角层数
     9             if nums-l==0: #如果当前层数满足条件
    10                 return traingle #返回杨辉三角
    11             else:
    12                 i=0  
    13                 temp=[1] #初始第n层的数字列表
    14                 while i<l-1: 
    15                     temp.append(traingle[l-1][i]+traingle[l-1][i+1])#向列表中添加元素
    16                     i+=1 
    17                 temp.append(1) #加上列表最后一个元素
    18                 traingle.append(temp) #增加杨辉三角层数
    19                 return rows(nums,traingle) #再次调用rows函数
    20         
    21         if numRows==0: #单独考虑0
    22             return []
    23         if numRows==1: #单独考虑1
    24             return [[1]]
    25         else:
    26             traingle=[[1],[1,1]] #初始为前两层的杨辉三角
    27             return rows(numRows,traingle)
    
    
  • 相关阅读:
    51nod1376 最长递增子序列的数量
    51nod1201 整数划分
    51nod1202 子序列个数
    51nod 博弈论水题
    51nod1052 最大M子段和
    51nod1678 lyk与gcd
    51nod1262 扔球
    BZOJ2763, 最短路
    吃西瓜 最大子矩阵 三维的。 rqnoj93
    noip2015 信息传递 强连通块
  • 原文地址:https://www.cnblogs.com/19991201xiao/p/8442907.html
Copyright © 2011-2022 走看看