"Leetcode" Unique Paths in JAVA

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?

My first reaction is recursion ~ ~ ~ Every step below is equivalent to the case of becoming m-1,n or m,n-1

In other words: ways[m][n]=ways[m-1][n]+ways[m][n-1]+2

Why is it 2? Because you can go to the right or go down two things-until the end of the right or left, there is only one way to go

So my first method:

int x=0;int y=0;public int uniquepaths (int m, int n) {if (x==m-1| | y==n-1) return 1;return uniquepaths (m-1,n) +uniquepaths (m,n-1) +2;}
But you'll find out right away ... This thing is out of time.

public class Uniquedepaths {public int uniquepaths (int m,int n) {int[][] rec = new Int[m][n];for (int i=0;i<m;i++) rec[i][ 0]=1;for (int j=0;j<n;j++) rec[0][j]=1;for (int p=1;p<m;p++) for (int q=1;q<n;q++) rec[p][q]=rec[p-1][q]+rec[p ][q-1];return rec[m-1][n-1];}}

Solved ~ ~ ~

"Leetcode" Unique Paths in JAVA

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.