题目描述:
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?
3 * 7的example
一开始无脑了一下,决定用递归:
a[m,n]=a[m-1,n] + a[m,n-1]
class Solution(object):
def uniquePaths(self, m, n):
if m == 1 or n == 1:
return 1
return self.uniquePaths(m,n-1) + self.uniquePaths(m-1,n)
自然是超时
后决定迭代计算:有两种顺序,先从左到右遍历一行,再从上到下遍历每一行,最左边初始化为1,其余的元素为其左和其上元素之和。这样细看空间需要m*n,想到了简化空间,我们容易知道输入m,n的次序不影响结果,我们可以只记录h = min(m,n)个值,我们假定高度值为h,也就是上图中对应的3,假设中间值存在数组tmp中,那么tmp[0]是1并保持不变,以后更新的时候将tmp[i] = tmp[i](旧值,相当于左侧元素)+ tmp[i-1](新值,相当于上侧元素)
class Solution(object):
def uniquePaths(self, m, n):
h = min(m,n)
w = max(m,n)
tmp = [1] * h
for i in range(1,w):
for j in range(1,h):
tmp[j] = tmp[j]+tmp[j-1]
return tmp[h-1]