LeetCode Unique Paths

Source: Internet
Author: User

LeetCode Unique Paths
Solving LeetCode with Unique Paths

Original question

The number of different paths from the start point to the end point of a robot can only go to the right or down.

Note:

The maximum grid size is 100*100.

Example:

Input: m = 3, n = 7

Output: 28

Solutions

A common primary school student's Mathematical Olympiad problem can be solved by means of permutation and combination. A total of steps (S-1) + (n-1) should be taken, m-1) steps down, (n-1) to the right, and there is a formulamCn = n!/m!(n-m)!, You can use the following code to solve the problem:

import mathclass Solution(object):    def uniquePaths(self, m, n):        """        :type m: int        :type n: int        :rtype: int        """        m -= 1        n -= 1        return math.factorial(m+n) / (math.factorial(n) * math.factorial(m))

Of course, a more common approach is dynamic planning. To reach a grid, you only need to come over from the grid above it or on the left. Recursive relationship:dp[i][j]=dp[i-1][j]+dp[i][j-1]. The initialization condition is that there is only one path on the left and the top, and all grids are initialized to 1 during initialization.

AC Source Code
class Solution(object):    def uniquePaths(self, m, n):        """        :type m: int        :type n: int        :rtype: int        """        dp = [[1 for __ in range(n)] for __ in range(m)]        for i in range(1, n):            for j in range(1, m):                dp[j][i] = dp[j - 1][i] + dp[j][i - 1]        return dp[m - 1][n - 1]if __name__ == "__main__":    assert Solution().uniquePaths(3, 7) == 28

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.