Skip to content

Commit 2f8c738

Browse files
authored
feat(uniquepaths): add solution for unique paths problem (#716)
* feat(uniquepaths): add solution for unique paths problem * fix: Remove extra unused memory
1 parent 2354582 commit 2f8c738

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

dynamic/uniquepaths.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// See https://leetcode.com/problems/unique-paths/
2+
// author: Rares Mateizer (https://github.com/rares985)
3+
package dynamic
4+
5+
// UniquePaths implements the solution to the "Unique Paths" problem
6+
func UniquePaths(m, n int) int {
7+
if m <= 0 || n <= 0 {
8+
return 0
9+
}
10+
11+
grid := make([][]int, m)
12+
for i := range grid {
13+
grid[i] = make([]int, n)
14+
}
15+
16+
for i := 0; i < m; i++ {
17+
grid[i][0] = 1
18+
}
19+
20+
for j := 0; j < n; j++ {
21+
grid[0][j] = 1
22+
}
23+
24+
for i := 1; i < m; i++ {
25+
for j := 1; j < n; j++ {
26+
grid[i][j] = grid[i-1][j] + grid[i][j-1]
27+
}
28+
}
29+
30+
return grid[m-1][n-1]
31+
}

dynamic/uniquepaths_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package dynamic
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestUniquePaths(t *testing.T) {
8+
testCases := map[string]struct {
9+
m int
10+
n int
11+
want int
12+
}{
13+
"negative sizes": {-1, -1, 0},
14+
"empty matrix both dimensions": {0, 0, 0},
15+
"empty matrix one dimension": {0, 1, 0},
16+
"one element": {1, 1, 1},
17+
"small matrix": {2, 2, 2},
18+
"stress test": {1000, 1000, 2874513998398909184},
19+
}
20+
21+
for name, test := range testCases {
22+
t.Run(name, func(t *testing.T) {
23+
if got := UniquePaths(test.m, test.n); got != test.want {
24+
t.Errorf("UniquePaths(%v, %v) = %v, want %v", test.m, test.n, got, test.want)
25+
}
26+
})
27+
}
28+
}

0 commit comments

Comments
 (0)