62. Unique Paths

# medium

Solution:

  1. Initilize down and left parts of the grid with number of 1

  2. Compute down-up or left-right grid based on known grid. f(x,y) = f(x-1,y) + f(x,y-1)

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] paths = new int[m][n];
        for(int[] arr: paths)
            Arrays.fill(arr, 1);
        for(int i = 0; i < m; i ++)
            paths[i][0] = 1;
        
        for(int i = 1; i < m; i ++)
            for(int j = 1; j < n; j ++)
                paths[i][j] = paths[i-1][j] + paths[i][j-1];
        
        return paths[m-1][n-1];
    }
}

Last updated

Was this helpful?