Open azl397985856 opened 1 year ago
动态规划
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0]*m for _ in range(n)]
for i in range(n):
for j in range(m):
if i==0 or j==0:
dp[i][j] = 1
else:
dp[i][j] = dp[i-1][j]+dp[i][j-1]
return dp[n-1][m-1]
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n] + [[1] + [0] * (n - 1)] * (m - 1)
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
DP
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp=[[1]*n for _ in range(m)]
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[m-1][n-1]
复杂度分析
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n] + [[1] + [0] * (n - 1)] * (m - 1)
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
# 思路
# 1.定义状态:不同路径的数量 dp[i][j]含义:到位置(i, j)一共有几条路径
# 2.初始化状态:初始化第一行和第一列,均为1
# 3.状态转移:dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n] + [[1] + [0] * (n - 1)] * (m - 1)
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]
class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[1] n] + [[1] + [0] (n - 1)] * (m - 1) for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[-1][-1]
/* 思路: 动态规划 复杂度: 时间复杂度:O(mn) 空间复杂度:O(mn)
*/
func uniquePaths(m, n int) int {
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
dp[i][0] = 1
}
for j := 0; j < n; j++ {
dp[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
return dp[m-1][n-1]
}
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
cur = [1] * n
for i in range(1, m):
for j in range(1, n):
cur[j] += cur[j-1]
return cur[-1]
62. 不同路径
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/unique-paths/
前置知识
暂无
题目描述