码迷,mamicode.com
首页 > 编程语言 > 详细

Unique Paths @ Python Leetcode EPI 17.4

时间:2014-08-25 06:33:53      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   for   ar   

 

Unique Paths

 

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?

bubuko.com,布布扣

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

Note: m and n will be at most 100.

This is also EPI 17.4. Number of Ways.

Location:  P403. Elements of Programming Interviews

Idea:

Here is an example: m =5, n =5

bubuko.com,布布扣

The number of ways to get from (0; 0) to (i; j) for 0 <= i <= 4;  0 <= j <=  4.

 

 

Solution 1:

 

1 class Solution:
2     # @return an integer
3     def uniquePaths(self, m, n):
4         f = [[1 for i in range(n)] for i in range(m)]
5         for i in range(1,m):
6             for j in range(1,n):
7                 f[i][j] = f[i-1][j] + f[i][j-1]
8         return f[-1][-1]

time complexity is: O(mn)
space complexity is: O(nm)

 

Solution 2:

 1 class Solution:
 2     # @return an integer
 3     def uniquePaths(self, m, n):
 4         if n < m: m, n = n, m
 5         f = [1] * m
 6         for i in range(1, n):
 7             prev_res = 0
 8             for j in range(m):
 9                 f[j] = f[j] + prev_res
10                 prev_res = f[j]
11         return f[-1]

time complexity is: O(mn)
space complexity is: O(min(m, n))

 

Unique Paths @ Python Leetcode EPI 17.4

标签:style   blog   http   color   os   io   strong   for   ar   

原文地址:http://www.cnblogs.com/asrman/p/3934162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!