mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Add Pascal's Triangle based solution for Unique Paths problem.
This commit is contained in:
parent
d8fb6579b1
commit
b73ddec94d
@ -118,7 +118,7 @@ a set of rules that precisely define a sequence of operations.
|
||||
* `B` [Tower of Hanoi](src/algorithms/uncategorized/hanoi-tower)
|
||||
* `B` [Square Matrix Rotation](src/algorithms/uncategorized/square-matrix-rotation) - in-place algorithm
|
||||
* `B` [Jump Game](src/algorithms/uncategorized/jump-game) - backtracking, dynamic programming (top-down + bottom-up) and greedy examples
|
||||
* `B` [Unique Paths](src/algorithms/uncategorized/unique-paths) - backtracking and dynamic programming examples
|
||||
* `B` [Unique Paths](src/algorithms/uncategorized/unique-paths) - backtracking, dynamic programming and Pascal's Triangle based examples
|
||||
* `A` [N-Queens Problem](src/algorithms/uncategorized/n-queens)
|
||||
* `A` [Knight's Tour](src/algorithms/uncategorized/knight-tour)
|
||||
|
||||
|
@ -94,6 +94,13 @@ the bottom right one with number `3`.
|
||||
|
||||
**Auxiliary Space Complexity**: `O(m * n)` - since we need to have DP matrix.
|
||||
|
||||
### Pascal's Triangle Based
|
||||
|
||||
This question is actually another form of Pascal Triangle.
|
||||
|
||||
The corner of this rectangle is at `m + n - 2` line, and
|
||||
at `min(m, n) - 1` position of the Pascal's Triangle.
|
||||
|
||||
## References
|
||||
|
||||
- [LeetCode](https://leetcode.com/problems/unique-paths/description/)
|
||||
|
@ -0,0 +1,12 @@
|
||||
import uniquePaths from '../uniquePaths';
|
||||
|
||||
describe('uniquePaths', () => {
|
||||
it('should find the number of unique paths on board', () => {
|
||||
expect(uniquePaths(3, 2)).toBe(3);
|
||||
expect(uniquePaths(7, 3)).toBe(28);
|
||||
expect(uniquePaths(3, 7)).toBe(28);
|
||||
expect(uniquePaths(10, 10)).toBe(48620);
|
||||
expect(uniquePaths(100, 1)).toBe(1);
|
||||
expect(uniquePaths(1, 100)).toBe(1);
|
||||
});
|
||||
});
|
13
src/algorithms/uncategorized/unique-paths/uniquePaths.js
Normal file
13
src/algorithms/uncategorized/unique-paths/uniquePaths.js
Normal file
@ -0,0 +1,13 @@
|
||||
import pascalTriangle from '../../math/pascal-triangle/pascalTriangle';
|
||||
|
||||
/**
|
||||
* @param {number} width
|
||||
* @param {number} height
|
||||
* @return {number}
|
||||
*/
|
||||
export default function uniquePaths(width, height) {
|
||||
const pascalLine = width + height - 2;
|
||||
const pascalLinePosition = Math.min(width, height) - 1;
|
||||
|
||||
return pascalTriangle(pascalLine)[pascalLinePosition];
|
||||
}
|
Loading…
Reference in New Issue
Block a user