1.不同路径https://leetcode-cn.com/problems/unique-paths/
看到这题,我第一想到的也是组合数学。就直接计算一下组合数就行了
1 class Solution: 2 def uniquePaths(self, m: int, n: int) -> int: 3 return comb(m + n - 2, n - 1)
在官方解答看到了动态规划的解法,也学习了一下动态规划的思想。当前状态为前一个状态的和,此处的前一个状态有2种(从左边走过来,从上边走过来)
所以状态转移方程为f(i, j) = f(i-1, j) + f(i, j-1)
1 class Solution: 2 def uniquePaths(self, m: int, n: int) -> int: 3 f = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)] 4 print(f) 5 for i in range(1, m): 6 for j in range(1, n): 7 f[i][j] = f[i - 1][j] + f[i][j - 1] 8 return f[m - 1][n - 1]
这里
f = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)]
把我惊艳了一下,又学到了新的python的语法,如果是我应该是傻傻地用for循环去创建吧
这里通过for _ in range(m - 1)避免浅复制问题https://blog.csdn.net/qq_21997625/article/details/105694880
复习了一下python list运算
https://blog.csdn.net/jp_666/article/details/98055191
https://www.runoob.com/python3/python3-list-operator.html
2.爬楼梯https://leetcode-cn.com/problems/climbing-stairs/