您的位置:首页 > 产品设计 > UI/UE

LeetCode解题笔记62 Unique Paths

2018-01-18 15:33 344 查看
原题目:
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?


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步,向右n步。尝试用python写了两种
第一种采用了python的迭代工具模块,但是超时:
from itertools import combinations
class Solution:
def uniquePaths(self, m, n):
return len(list(combinations([0]*(m+n-2),min(m,n)-1)))于是尝试自己重写一个单独的直接求组合数
class Solution:
def uniquePaths(self, m, n):
x = min(m,n)
num = 1
dem = 1
for i in range(1,x):
num *= m+n-1-i
dem *= i
return int(num/dem)
可以通过,事实证明有时候简单的重现比现成的模块方法要快,当有冗余计算的时候。

第二种思路就是根据动态规划思想:
class Solution:
def uniquePaths(self, m, n):
res = [0]*n
res[0]=1
for i in range(m):
for j in range(1,n):
res[j] += res[j-1]
return res[n-1]具体思路还没想明白
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode