[BackTracking]119. Pascal's Triangle II

  • 分类:BackTracking
  • 时间复杂度: O(n^2)
  • 空间复杂度: O(n^2) or O(k)

119. Pascal's Triangle II

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

[BackTracking]119. Pascal's Triangle II_第1张图片
image.png

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

代码:

原来想的代码:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        
        if rowIndex==0:
            return [1]
        prev=self.getRow(rowIndex-1)
        current=[1 for i in range(rowIndex+1)]
        for i in range(1,rowIndex):
            current[i]=prev[i-1]+prev[i]
        return current

迭代DP,自己写的O(k)代码:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        
        if rowIndex==0:
            return [1]
        dp={0:[1 for i in range(rowIndex+1)],1:[1 for i in range(rowIndex+1)]}
        for j in range(1,rowIndex+1):
            for i in range(1,j):
                dp[j%2][i]=dp[(j-1)%2][i-1]+dp[(j-1)%2][i]
        return dp[(rowIndex)%2]

迭代,Youtube上小梦想家的代码:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        
        res=[1]+[0]*rowIndex
        for i in range(1,rowIndex+1):
            for j in range(i,0,-1):
                res[j]=res[j]+res[j-1]
        
        return res

讨论:

1.这道题O(k)的方法相当于一个DP的解法
2.小梦想家的方法真的很简洁很舒服orz,我佛

你可能感兴趣的:([BackTracking]119. Pascal's Triangle II)