Backtracking
1 | class Solution { |
Remarks:
- TC: $O(2^{m+n})$, time limit exceeded for big inputs; SC: $O(1)$.
Math (Combination) OPTIMIZED
1 | class Solution { |
Remarks:
- The idea is: from $(0,0)$ to $(m-1, n-1)$, we only need to take $(m-1)$ steps of going “down” and $(n-1)$ steps of going “right”. So actually we are just trying to figure out the combination of selecting $(m - 1)$ steps of going down, out of $(m - 1) + (n - 1)$ steps in total, that is $C(m+n-2, m-1) = \cfrac{(m+n-2)!}{(m-1)!(n-1)!}$.
- TC: $O(\min(m,n))$, SC: $O(1)$.
Dynamic Programming
1 | class Solution { |
Remarks:
- Idea: each block’s path count is the sum of the one on the top of it and left of it, $dp[i][j] = dp[i-1][j] + dp[j][j-1]$.
- TC: $O(m\times n)$, SC: $O(m\times n)$.