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):
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]具体思路还没想明白
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 62 Unique Paths 解题报告
- Leetcode62: Unique Paths
- Leetcode[62]-Unique Paths
- LeetCode62——Unique Paths
- Leetcode解题笔记-Merge sorted Array
- LeetCode 62 Unique Paths
- LeetCode解题笔记45 Jump Game II
- [LeetCode] Unique Paths 解题报告
- Leetcode解题笔记 169.Majority Element [Easy]
- LeetCode_62---Unique Paths
- leetcode---62. Unique Paths
- 【LeetCode】Spiral Matrix解题笔记
- Leetcode解题笔记-Plusone
- Leetcode解题笔记-Contains Duplicate && Contains Duplicate II&&Contain Duplicate III
- leetcode解题笔记-Copy List with Random Pointer
- leetcode解题笔记:Regular Expression Matching
- LeetCode62——Unique Paths
- Leetcode62 Unique Paths
- LeetCode解题笔记204 Count Primes
- leetcode 62:Unique Paths