Memoised solution using a 2-D array (Java 1ms)


  • 0
    M
    public class Solution {
        private int[][] arr;
        public int uniquePaths(int m, int n) {
            if(m < 0 || n < 0){
                return 0;
            }
            if(m-1 == 0 || n-1 == 0){
                return 1;
            }
            if(arr == null){
                arr = new int[m+1][n+1];
                for(int[] row: arr){
                    Arrays.fill(row, -1);
                }
            }
            if(arr[m][n] == -1){
                arr[m][n] = uniquePaths(m-1, n) + uniquePaths(m, n-1);
            }
            return arr[m][n];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.