[LeetCode] [Java] Unique Paths

Source: Internet
Author: User

[LeetCode] [Java] Unique Paths
Question:

 

A robot is located at the top-left corner of a m x n grid (marked 'start' in the dimo-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 dimo-below ).

How many possible unique paths are there?

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

Given a grid structure of m x n, a robot moves from the upper-left corner of the grid to the lower-right corner, and can only move one cell to the right or down at a time. Algorithm Analysis: * dynamic planning:
*
* Specifically, define m * n-dimensional two-dimensional array dp [] [], dp [I] [j] to indicate the number of paths from s to the lattice (I, j, * Now we can think about writing the dp equation. By observing the grid features and walk, we can find that there are only two ways to reach (I, j), * the first is from (I-1, j) down to (I, j ), the second is from (I, J-1) to (I, j), while dp [I] [J-1] and dp [I-1] [j] Are the intermediate computing results that have been saved, * so we can obtain the recurrence equation dp [I] [j] = dp [I] [J-1] + dp [I-1] [j]. Therefore, the total number of paths from (0, 0) to the right and bottom of the grid can be calculated continuously. * until the total number of paths in the dp [M-1] [n-1] is calculated, the algorithm time complexity is O (mn ), the space complexity is O (mn ).
*
The algorithm is as follows:
public class Solution {    public int uniquePaths(int m, int n)     {        //dp[i][j] = dp[i-1][j] + dp[i][j-1];        int [][] dp = new int[m][n];        for(int i = 0; i < m; i++)            dp[i][0] = 1;        for(int j = 0; j < n; j++)            dp[0][j] = 1;        for(int i = 1; i < m; i++)        {            for(int j = 1; j< n; j++)                dp[i][j] = dp[i-1][j] + dp[i][j-1];        }        return dp[m-1][n-1];    }}


 

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.