卖萌的弱渣

I am stupid, I am hungry.

Unique Paths

Unique Paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?

Solution

  • Time: O(n2)
  • path[m][n]: number of unique paths for m * n grid

    paths[m][n] = paths[m-1][n] + paths[m][n-1]

(Unique-Paths.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    """
    @param n and m: positive integer(1 <= n , m <= 100)
    @return an integer
    """
    def uniquePaths(self, m, n):
        # write your code here
        paths = [[0] * n for i in range(m)]
        paths[0][0] = 1
        if n==1 or m<=1:
            return 1
        for i in range(0, m):
            paths[i][0] = 1
        for i in range(0, n):
            paths[0][i] = 1

        for i in range(1, m):
            for j in range(1, n):
                paths[i][j] = paths[i-1][j] + paths[i][j-1]
        return paths[m-1][n-1]