Unique Paths

  • tags: [DP_Matrix]

Question

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?

Note
m and n will be at most 100.

题解

题目要求:给定m x n矩阵,求左上角到右下角的路径总数,每次只能向左或者向右前进。按照动态规划中矩阵类问题的通用方法:

  1. State: f[m][n] 从起点到坐标(m,n)的路径数目
  2. Function: f[m][n] = f[m-1][n] + f[m][n-1] 分析终点与左边及右边节点的路径数,发现从左边或者右边到达终点的路径一定不会重合,相加即为唯一的路径总数
  3. Initialization: f[i][j] = 1, 到矩阵中任一节点均至少有一条路径,其实关键之处在于给第0行和第0列初始化,免去了单独遍历第0行和第0列进行初始化
  4. Answer: f[m - 1][n - 1]
class Solution:
    # @return an integer
    def uniquePaths(self, m, n):
        if m == 1 and n == 1:
            list = [[1]]
        elif m == 1 and n > 1:
            list = [[1 for i in range(n)]]
        elif m > 1 and n == 1:
            list = [[1] for i in range(m)]
        else:
            list = [[0 for i in range(n)] for i in range(m)]
            for i in range(0, n):
                list[0][i] = 1
            for i in range(0, m):
                list[i][0] = 1
            for i in range(1, m):
                for j in range(1, n):
                    list[i][j] = list[i-1][j] + list[i][j-1]
        return list[m-1][n-1]

sol = Solution()
sol.uniquePaths(3,3)
import math
class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        ans = 1;tmp = 1;m -= 1;n -= 1
        t = min(m,n)
        i = 0
        while i < t:
            ans *= (m + n - i)
            tmp *= (t - i)
            i += 1
        return ans /tmp

sol = Solution()
sol.uniquePaths(3,3)

results matching ""

    No results matching ""