classSolution: defuniquePaths(self, m: int, n: int) -> int: dp = [[1]*n] + [[1]+[0] * (n-1) for _ inrange(m-1)] #print(dp) for i inrange(1, m): for j inrange(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1]
[1]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { publicintuniquePaths(int m, int n) { int[][] dp = newint[m][n]; for (inti=0; i < n; i++) dp[0][i] = 1; for (inti=0; i < m; i++) dp[i][0] = 1; for (inti=1; i < m; i++) { for (intj=1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } }
优化1:空间复杂度 $O(2n)$
[2]
1 2 3 4 5 6 7 8 9
classSolution: defuniquePaths(self, m: int, n: int) -> int: pre = [1] * n cur = [1] * n for i inrange(1, m): for j inrange(1, n): cur[j] = pre[j] + cur[j-1] pre = cur[:] return pre[-1]
[2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintuniquePaths(int m, int n) { int[] pre = newint[n]; int[] cur = newint[n]; Arrays.fill(pre, 1); Arrays.fill(cur,1); for (inti=1; i < m;i++){ for (intj=1; j < n; j++){ cur[j] = cur[j-1] + pre[j]; } pre = cur.clone(); } return pre[n-1]; } }
优化2:空间复杂度 $O(n)$
[3]
1 2 3 4 5 6 7
classSolution: defuniquePaths(self, m: int, n: int) -> int: cur = [1] * n for i inrange(1, m): for j inrange(1, n): cur[j] += cur[j-1] return cur[-1]
[3]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicintuniquePaths(int m, int n) { int[] cur = newint[n]; Arrays.fill(cur,1); for (inti=1; i < m;i++){ for (intj=1; j < n; j++){ cur[j] += cur[j-1] ; } } return cur[n-1]; } }