Sunday, September 7, 2014

Leetcode: Unique Paths @Python

Dynamic programming solution:
class Solution:
    # @return an integer
    def uniquePaths(self, m, n):
        if m<=0 or n<=0: return 1
        dp=[[1]*n for i in range(m)]
        for j in range(1,m):
            for i in range(1,n):
                dp[j][i]=dp[j-1][i]+dp[j][i-1]
        return dp[m-1][n-1]
Math solution:
class Solution:
    # @return an integer
    def uniquePaths(self, m, n):
        return math.factorial(m + n - 2) / (math.factorial(m - 1) * math.factorial(n - 1))        
Math solution is actually easy to understand. The robot need to make (m-1) down moves and (n-1) right moves to get to the destination. Each different sequence which consists of (m-1) down moves and (n-1) right moves represents a unique path. The number of unique paths equals to the combinatorial number selecting (n-1) right moves from all (m+n-2) moves.

No comments :

Post a Comment