Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Contribute: Added algorithm and tests for Unique Paths DP problem#1118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
Jaiharishan wants to merge6 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromJaiharishan:master
Open
Show file tree
Hide file tree
Changes fromall 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
39 changes: 39 additions & 0 deletionsDynamic-Programming/UniquePaths.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/*
* 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/
* Problem Statement:
* There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.
* Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
* Approach:
* As the given problem can be reduced to smaller and overlapping sub problems, we can use dynamic programming and memoization to solve this problem.
* Time complexity: O(M * N) (M->ROWS | N->COLS)
* Space complexity: O(M * N) (M->ROWS | N->COLS)
*/

/**
* @param {number} rows
* @param {number} cols
* @return {number}
*/

// 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 }
7 changes: 7 additions & 0 deletionsDynamic-Programming/tests/UniquePaths.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
import { uniquePaths } from '../UniquePaths'

test('Test case for UniquePaths', () => {
expect(uniquePaths(3, 7)).toBe(28)
expect(uniquePaths(3, 2)).toBe(3)
expect(uniquePaths(8, 14)).toBe(77520)
})

[8]ページ先頭

©2009-2025 Movatter.jp