简繁EN

LeetCodeNo. 111

【LeetCode with Python】 62. Unique Paths

目錄

題目

原題頁面:https://leetcode.com/problems/unique-paths/
題目型別:Array, Dynamic Programming
難度評價:Medium
類似題目:(M) Unique Paths II, (M) Minimum Path Sum, (H) Dungeon Game

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?

robot_maze
Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


分析

用數學中的排列組合來解題,從(m+n-2)次選擇中選出(m-1)次向下走。
這道題跟“n階臺階,每次一步或兩步,總共多少種走法”一樣,也可以用動態規劃解題,不過這裡是二維動態規劃,而後者是一維動態規劃。Unique Paths還比較簡單,所以可用排列組合快速解題,但是Unique Paths II這道題,就只能用動態規劃了。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
# @return an integer
def uniquePaths(self, m, n):
if 0 == m or 0 == n:
return 1
up = 1
for i in range(m + n - 2, n - 1, -1):
up *= i
down = 1
for j in range(1, m):
down *= j
return up / down

本文地址:https://xnerv.wang/zh-tw/leetcode-unique-paths/