LeetCode(力扣)62. 不同路径Python

LeetCode62. 不同路径

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/unique-paths/
LeetCode(力扣)62. 不同路径Python_第1张图片

代码

递归

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        if m == 1 or n == 1:
            return 1
        return self.uniquePaths(m, n - 1) + self.uniquePaths(m - 1, n)

动态

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[0] * n for _ in range(m)]
        for i in range(n):
            dp[0][i] = 1
        for i in range(m):
            dp[i][0] = 1
        
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
        return dp[m - 1][n - 1]

你可能感兴趣的:(leetcode,python,算法,职场和发展)