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