Skip to content

Commit 781a7cf

Browse files
committed
Contribute: Added algorithm for Unique Paths problem
1 parent 9528c71 commit 781a7cf

File tree

3 files changed

+51
-12
lines changed

3 files changed

+51
-12
lines changed

Dynamic-Programming/UniquePaths.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* A Dynamic Programming based solution for calculating the number ways to travel from Top-Left of the matrix to Bottom-Right of the matrix
3+
* https://leetcode.com/problems/unique-paths/
4+
*/
5+
6+
// Return the number of unique paths, given the dimensions of rows and columns
7+
8+
const uniquePaths = (rows, cols) => {
9+
let dp = new Array(cols).fill(1)
10+
11+
for (let i = 1; i < rows; i++) {
12+
const tmp = []
13+
14+
for (let j = 0; j < cols; j++) {
15+
if (j === 0) {
16+
tmp[j] = dp[j]
17+
} else {
18+
tmp[j] = tmp[j - 1] + dp[j]
19+
}
20+
}
21+
dp = tmp
22+
}
23+
return dp.pop()
24+
}
25+
26+
export { uniquePaths }
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { uniquePaths } from '../UniquePaths'
2+
3+
test('Base Case 1', () => {
4+
const rows = 3
5+
const cols = 7
6+
expect(uniquePaths(rows, cols)).toBe(28)
7+
})
8+
9+
test('Base Case 2', () => {
10+
const rows = 3
11+
const cols = 2
12+
expect(uniquePaths(rows, cols)).toBe(3)
13+
})
14+
15+
test('Base Case 3', () => {
16+
const rows = 8
17+
const cols = 14
18+
expect(uniquePaths(rows, cols)).toBe(77520)
19+
})

package-lock.json

Lines changed: 6 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)