Java DP starting from the Finish: O(n*m)


  • 0
    T

    Similar to another post, but starts from the Finish location in the board. In my opinion, slightly more intuitive, but to each their own:

    public class Solution {
        public int uniquePaths(int m, int n) {
            if (m == 0 || n == 0) return 0;
            return unique(m, n);
        }
        
        private int unique(int m, int n) {
            int[][] board = new int[m][n];
            
            board[m-1][n-1] = 0;
            
            // fill bottom row
            for (int i = 0; i < n; i++) 
                board[m-1][i] = 1;
            
            // fill right column
            for (int i = 0; i < m; i++) 
                board[i][n-1] = 1;
            
            for (int i = m-2; i >= 0; i--)        // rows
                for (int j = n-2; j >= 0; j--)    // columns
                    board[i][j] = board[i+1][j] + board[i][j+1];
                    
            return board[0][0];
        }
    }
    

Log in to reply
 

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