The Unique Path leetcode Python

Source: Internet
Author: User

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 is there?




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

There are two ways of solving this problem.

1. Direct mathematical expression Choose M-1 from M+n-2

Class solution:    # @return An integer    def FAC (self,n):        if N==1 or n==0:            return 1        return N*SELF.FAC ( n-1)    def uniquepaths (self, M, n):        if M==1 or n==1:            return 1        val1=self.fac (m+n-2)        VAL2=SELF.FAC ( m-1)        Val3=self.fac (n-1)        result=val1/(VAL2*VAL3)        return result     


2. Dynamic planning, each step is adjacent to the nearest lattice and.

The code is as follows

Class solution:    # @return An integer    def uniquepaths (self, M, n):        dp=[[0 for index in range (n)] for index in R Ange (m)] for        row in range (m):            dp[row][0]=1 for Col in        Range (n):            dp[0][col]=1 for row in        range (1,m): For            col in Range (1,n):                dp[row][col]=dp[row-1][col]+dp[row][col-1]        return dp[m-1][n-1]        


The Unique Path leetcode Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.