美文网首页
[BackTracking]118. Pascal's Tria

[BackTracking]118. Pascal's Tria

作者: 野生小熊猫 | 来源:发表于2019-02-24 10:27 被阅读0次
    • 分类:BackTracking
    • 时间复杂度: O(n^2)
    • 空间复杂度: O(n^2)

    118. Pascal's Triangle

    Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

    image.png

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

    代码:

    class Solution:
        def generate(self, numRows: int) -> List[List[int]]:
            
            res=[]
            
            if numRows==0:
                return res
            
            self.helper(numRows,res)
            return res
        
        def helper(self,numRows,res):
            
            if numRows==1:
                res.append([1])
                return [1]
            
            prev=self.helper(numRows-1,res)
            current=[1 for i in range(numRows)]
            for i in range(1,numRows-1):
                current[i]=prev[i-1]+prev[i]
            res.append(current)
            return current
    

    讨论:

    1.这道题确实是个简单题,用迭代或者递归都可以做出来!

    相关文章

      网友评论

          本文标题:[BackTracking]118. Pascal's Tria

          本文链接:https://www.haomeiwen.com/subject/dgevyqtx.html