Skip to content

Commit 8c03cfc

Browse files
committed
feat: solve unique paths
1 parent 981f201 commit 8c03cfc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

unique-paths/GangBean.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.math.BigDecimal;
2+
3+
class Solution {
4+
/**
5+
1. understanding
6+
- To reach destination, you have to move bottom direction in m-1 times, and move to right direction in n-1 times.
7+
- in example 2, [(DDR), (DRD), (RDD)] is the paths.
8+
- so, the number of paths are combinations of (m-1) D and (n-1) R
9+
- (m+n-2)!/(m-1)!(n-1)!, where ! means factorial, n! = 1*2*...*n
10+
- factorial[n]: n!
11+
2. complexity
12+
- time: O(m+n)
13+
- space: O(m+n)
14+
*/
15+
public int uniquePaths(int m, int n) {
16+
BigDecimal[] dp = new BigDecimal[m+n];
17+
Arrays.fill(dp, BigDecimal.ONE);
18+
for (int num = 2; num < m+n; num++) {
19+
dp[num] = dp[num-1].multiply(new BigDecimal(num));
20+
}
21+
return dp[m+n-2].divide(dp[m-1]).divide(dp[n-1]).intValue();
22+
}
23+
}
24+

0 commit comments

Comments
 (0)