|
| 1 | +/* |
| 2 | +62. Unique Paths |
| 3 | +Medium |
| 4 | +
|
| 5 | +
|
| 6 | +There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). |
| 7 | +The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time. |
| 8 | +Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner. |
| 9 | +
|
| 10 | +The test cases are generated so that the answer will be less than or equal to 2 * 109. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +
|
| 14 | +
|
| 15 | +Input: m = 3, n = 7 |
| 16 | +Output: 28 |
| 17 | +Example 2: |
| 18 | +
|
| 19 | +Input: m = 3, n = 2 |
| 20 | +Output: 3 |
| 21 | +Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: |
| 22 | +1. Right -> Down -> Down |
| 23 | +2. Down -> Down -> Right |
| 24 | +3. Down -> Right -> Down |
| 25 | + |
| 26 | +
|
| 27 | +Constraints: |
| 28 | +
|
| 29 | +1 <= m, n <= 100 |
| 30 | +*/ |
| 31 | + |
| 32 | +class Solution { |
| 33 | + public int solveR(int m,int n){ |
| 34 | + if(m==0 && n==0) return 1; |
| 35 | + if(m<0 || n<0) return 0; |
| 36 | + int up = solveR(m-1,n); |
| 37 | + int left = solveR(m,n-1); |
| 38 | + return up+left; |
| 39 | + } |
| 40 | + public int solveM(int m,int n,int dp[][]){ |
| 41 | + if(m==0 && n==0) return 1; |
| 42 | + if(m<0 || n<0) return 0; |
| 43 | + if(dp[m][n] !=-1){ |
| 44 | + return dp[m][n]; |
| 45 | + } |
| 46 | + int up =solveM(m-1,n,dp); |
| 47 | + int left =solveM(m,n-1,dp); |
| 48 | + dp[m][n]=up+left; |
| 49 | + return dp[m][n]; |
| 50 | + } |
| 51 | + public int solveTab(int m,int n, int dp[][]){ |
| 52 | + for(int i=0;i<m;i++){ |
| 53 | + for(int j=0;j<n;j++){ |
| 54 | + if(i==0 && j==0 ) dp[i][j] =1; |
| 55 | + else{ |
| 56 | + int up=0,left=0; |
| 57 | + if(i>0) up = dp[i-1][j]; |
| 58 | + if(j>0) left =dp[i][j-1]; |
| 59 | + dp[i][j] = up+left; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + return dp[m-1][n-1]; |
| 64 | + } |
| 65 | + public int solveSpaceOpt(int m,int n){ |
| 66 | + int prev[] =new int[n]; |
| 67 | + for(int i=0;i<m;i++){ |
| 68 | + int curr[] =new int[n]; |
| 69 | + for(int j=0;j<n;j++){ |
| 70 | + if(i==0 && j==0) curr[i]=1; |
| 71 | + else{ |
| 72 | + int up =0,left=0; |
| 73 | + if(i>0) up = prev[j]; |
| 74 | + if(j>0) left =curr[j-1]; |
| 75 | + curr[j] = up+left; |
| 76 | + } |
| 77 | + } |
| 78 | + prev = curr; |
| 79 | + } |
| 80 | + return prev[n-1]; |
| 81 | + } |
| 82 | + public int uniquePaths(int m, int n) { |
| 83 | + //return solveR(m-1,n-1); |
| 84 | + //int dp[][] =new int[m][n]; |
| 85 | + //Arrays.stream(dp).forEach(a -> Arrays.fill(a, -1)); |
| 86 | + //return solveM(m-1,n-1,dp); |
| 87 | + //return solveTab(m,n,dp); |
| 88 | + return solveSpaceOpt(m,n); |
| 89 | + } |
| 90 | +} |
0 commit comments