DevPath

← All problems

Unique Paths

Medium dynamic-programming · combinatorics

Description

A robot at the top-left of an m by n grid can move only right or down. Return the number of distinct paths to the bottom-right.

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]
}

Create a free account to submit solutions, track progress and save problems.

Create account