File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ input : 2D matrix
3+ output : the number of possible unique paths
4+ constraints :
5+ 1) range of m and n
6+ [1, 100]
7+
8+ solution 1) dfs?
9+ move right or move down.
10+ tc : O(mn)
11+ sc : O(mn)
12+
13+ solution 2) dp + tabulation
14+ let dp[i][j] the number of unique paths from starting point.
15+ there are only 2 way to get coordinate i, j
16+ 1) from i-1, j
17+ 2) from i, j-1
18+ dp[i][j] = dp[i-1][j] + dp[i][j-1]
19+
20+ tc : O(mn)
21+ sc : O(mn)
22+ */
23+
24+ class Solution {
25+ public int uniquePaths (int m , int n ) {
26+ int [][] dp = new int [m ][n ];
27+ for (int i = 0 ; i < m ; i ++) {
28+ for (int j = 0 ; j < n ; j ++) {
29+ if (i == 0 || j == 0 ) {
30+ dp [i ][j ] = 1 ;
31+ continue ;
32+ }
33+ dp [i ][j ] = dp [i ][j -1 ] + dp [i -1 ][j ];
34+ }
35+ }
36+ return dp [m -1 ][n -1 ];
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments