-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(uniquepaths): add solution for unique paths problem (#716)
* feat(uniquepaths): add solution for unique paths problem * fix: Remove extra unused memory
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// See https://leetcode.com/problems/unique-paths/ | ||
// author: Rares Mateizer (https://github.com/rares985) | ||
package dynamic | ||
|
||
// UniquePaths implements the solution to the "Unique Paths" problem | ||
func UniquePaths(m, n int) int { | ||
if m <= 0 || n <= 0 { | ||
return 0 | ||
} | ||
|
||
grid := make([][]int, m) | ||
for i := range grid { | ||
grid[i] = make([]int, n) | ||
} | ||
|
||
for i := 0; i < m; i++ { | ||
grid[i][0] = 1 | ||
} | ||
|
||
for j := 0; j < n; j++ { | ||
grid[0][j] = 1 | ||
} | ||
|
||
for i := 1; i < m; i++ { | ||
for j := 1; j < n; j++ { | ||
grid[i][j] = grid[i-1][j] + grid[i][j-1] | ||
} | ||
} | ||
|
||
return grid[m-1][n-1] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package dynamic | ||
|
||
import ( | ||
"testing" | ||
) | ||
|
||
func TestUniquePaths(t *testing.T) { | ||
testCases := map[string]struct { | ||
m int | ||
n int | ||
want int | ||
}{ | ||
"negative sizes": {-1, -1, 0}, | ||
"empty matrix both dimensions": {0, 0, 0}, | ||
"empty matrix one dimension": {0, 1, 0}, | ||
"one element": {1, 1, 1}, | ||
"small matrix": {2, 2, 2}, | ||
"stress test": {1000, 1000, 2874513998398909184}, | ||
} | ||
|
||
for name, test := range testCases { | ||
t.Run(name, func(t *testing.T) { | ||
if got := UniquePaths(test.m, test.n); got != test.want { | ||
t.Errorf("UniquePaths(%v, %v) = %v, want %v", test.m, test.n, got, test.want) | ||
} | ||
}) | ||
} | ||
} |