Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions Dynamic-Programming/UniquePaths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* A Dynamic Programming based solution for calculating the number ways to travel from Top-Left of the matrix to Bottom-Right of the matrix
* https://leetcode.com/problems/unique-paths/
*/

// Return the number of unique paths, given the dimensions of rows and columns

const uniquePaths = (rows, cols) => {
let dp = new Array(cols).fill(1)

for (let i = 1; i < rows; i++) {
const tmp = []

for (let j = 0; j < cols; j++) {
if (j === 0) {
tmp[j] = dp[j]
} else {
tmp[j] = tmp[j - 1] + dp[j]
}
}
dp = tmp
}
return dp.pop()
}

export { uniquePaths }
15 changes: 15 additions & 0 deletions Dynamic-Programming/tests/UniquePaths.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { uniquePaths } from '../UniquePaths'

describe('UniquePaths', () => {
it('uniquePaths for rows=3 and cols=7', () => {
expect(uniquePaths(3, 7)).toBe(28)
})

it('uniquePaths for rows=3 and cols=2', () => {
expect(climbStairs(3, 2)).toBe(3)
})

it('uniquePaths for rows=8 and cols=14', () => {
expect(climbStairs(8, 14)).toBe(77520)
})
})