Unique Paths
Medium dynamic-programming · combinatorics
Description
Constraints
1 <= m, n <= 20
Examples
Input: m = 3, n = 7
Output: 28
Hints (1)
- Each cell is the sum of the cell above and the cell to the left.
Solutions
Single-row DP. · Time O(m*n) · Space O(n)
func uniquePaths(m, n int) int {
row := make([]int, n)
for j := range row {
row[j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
row[j] += row[j-1]
}
}
return row[n-1]
}
Single-row DP. · Time O(m*n) · Space O(n)
function uniquePaths(m, n) {
const row = new Array(n).fill(1);
for (let i = 1; i < m; i++) for (let j = 1; j < n; j++) row[j] += row[j - 1];
return row[n - 1];
}
Single-row DP. · Time O(m*n) · Space O(n)
function uniquePaths($m, $n) {
$row = array_fill(0, $n, 1);
for ($i = 1; $i < $m; $i++) {
for ($j = 1; $j < $n; $j++) { $row[$j] += $row[$j - 1]; }
}
return $row[$n - 1];
}
Single-row DP. · Time O(m*n) · Space O(n)
def uniquePaths(m, n):
row = [1] * n
for _ in range(1, m):
for j in range(1, n):
row[j] += row[j - 1]
return row[n - 1]
Single-row DP. · Time O(m*n) · Space O(n)
function uniquePaths(m: number, n: number): number {
const row = new Array(n).fill(1);
for (let i = 1; i < m; i++) for (let j = 1; j < n; j++) row[j] += row[j - 1];
return row[n - 1];
}
Create a free account to submit solutions, track progress and save problems.
Create account