zoukankan      html  css  js  c++  java
  • LeetCode--118--杨辉三件I

    问题描述:

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

    在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:

    输入: 5
    输出:
    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    方法1:temp_list存储当前层的列表,当层数大于1时,用temp2_list存储其上一层的值,根据规则进行相加求和,每行第一个和最后一个append(1).

     1 class Solution(object):
     2     def generate(self, numRows):
     3         """
     4         :type numRows: int
     5         :rtype: List[List[int]]
     6         """
     7         if numRows == 0:
     8             return []
     9         if numRows == 1:
    10             return [[1]]
    11         z_list = []
    12         temp_list = [1]
    13         z_list.append(temp_list)
    14         for i in range(2,numRows+1):
    15             temp_list = []
    16             for j in range(0,i):
    17                 if j < 1:
    18                     temp_list.append(1)  
    19                 elif j >=1 and j < i - 1:
    20                     temp2_list = z_list[i - 2]
    21                     temp_list.append(temp2_list[j-1] + temp2_list[j]) 
    22                 elif j == i - 1:
    23                     temp_list.append(1)
    24             z_list.append(temp_list)
    25         return z_list

    方法2:用s[-1]表示上一层的列表。

     1 class Solution(object):
     2     def generate(self, numRows):
     3         """
     4         :type numRows: int
     5         :rtype: List[List[int]]
     6         """
     7         if(numRows==0):
     8             return([])
     9         if(numRows==1):
    10             return([[1]])
    11         s=[[1]]
    12         for i in range(1,numRows):
    13             t=[]
    14             for j in range(len(s[-1])+1):
    15                 if(j==0):
    16                     t.append(s[-1][0])
    17                 elif(j==len(s[-1])):
    18                     t.append(s[-1][-1])
    19                 else:
    20                     t.append(s[-1][j]+s[-1][j-1])
    21             s.append(t)
    22         return(s)

    2018-09-10 21:01:58

  • 相关阅读:
    codeforces 1060 B
    codeforces 1060 A
    牛客 国庆七天乐 day1 L
    BZOJ 1087: [SCOI2005]互不侵犯King
    codeforces 792CDivide by Three(两种方法:模拟、动态规划
    codeforces 797C Minimal string
    codeforces 110E Lucky Tree
    codeforces 798D
    2017福建省赛 FZU2272~2283
    Android -- Looper、Handler、MessageQueue等类之间关系的序列图
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9622950.html
Copyright © 2011-2022 走看看