ZhongKuo0228 / study

0 stars 0 forks source link

62. Unique Paths #118

Open fockspaces opened 10 months ago

fockspaces commented 10 months ago

use dp to solve the transfer state problem each cell cen only be arrived by top and left cell, so we can first init the starting point as 1, seems there's only one way to arrive. then we loop through each element from top-left to buttom-down

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[0 for _ in range(n)] for _ in range(m)]
        print(dp)
        dp[0][0] = 1
        for row in range(m):
            for col in range(n):
                if row == 0 and col == 0:
                    continue
                left = dp[row][col - 1] if col >= 1 else 0
                right = dp[row - 1][col] if row >= 1 else 0
                dp[row][col] = left + right
        return dp[-1][-1]